0

i have a dropdown list which gets populated by the content of a folder. When i save the page, the dropdown resets and does not show the selected image. Other options on the same page (color/text..) do save and keep the value.

Any ideas? I've tried with the "selected" function but it does not work in the way i used it.

Thanks everyone!

Code:

/*create the field*/

add_settings_field( 
    'psg_dyn_select_1', 
    __( 'Settings field description', 'wordpress' ), 
    'psg_dyn_select_1_render', 
    'pluginPage', 
    'psg_pluginPage_section' 
);

/*output the field*/

function psg_dyn_select_1_render ( ) {

$options = get_option( 'psg_settings' );
?>
<select name= 'psg_settings[psg_dyn_select_1]'>
   <?php foreach ( glob( plugin_dir_path( __FILE__ ) . "assets/images/*" ) as $filename){
   $filename = basename($filename);
   echo "<option value='" . $filename . "'>".$filename." </option>";}?>     
</select> 

0

You need to add a 'selected' value to the option output, so that the html displays the value that's saved in the psg_settings.

Something like this:

function psg_dyn_select_1_render ( ) {
    $options = get_option( 'psg_settings' );
    $files = glob( plugin_dir_path( __FILE__ ) . "assets/images/*" );
    ?>
    <select name= 'psg_settings[psg_dyn_select_1]'>
    <?php foreach ($files as $filename){
        $filename = basename($filename);
        $selected = ($filename == $options['psg_dyn_select_1']) ? 'selected="selected"' : '';
        echo "<option value='" . $filename . "' " . 
            $selected . ">".$filename." </option>";
    }?> 
    </select>
}

If that's not working, then you need to debug what the value of $options and $options['psg_dyn_select_1'] are in comparison to what's being output in your select dropdown (the values of $filename).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.