<select> tag not loading selected item when form load

I’m using a WordPress theme and I’m adding a new settings option using the WordPress settings API.

What I want to do is have a drop-down list that populates from the database of wordpress pages on my site and then have the user select the page they want for the particular option.

Read More

What is happening with my current code is that it will populate and select the page – even save it to my database, but when I open the options’ page again, however, it reverts the selection which is displayed to the default option – it isn’t changing anything in the database, it’s simply not displaying the option that is in the database when it loads. Any ideas?

here is the function im using to display the dropdown list :

 function  setting_dropdown_fn() {
$options = get_option('wellness_options');
echo "<select name='wellness_options[page_string]'>" ;
   $pages = get_pages(); 
  foreach ( $pages as $pagg ) {
$option = '<option value="' . get_page_link( $pagg->ID ) . '">';
$option .= $pagg->post_title;
$option .= '</option>';
echo $option;
  } 
echo '</select>';}

Related posts

Leave a Reply

1 comment

  1. You need to set the as the “selected” option when you output the drop down list. The HTML output (after page 3 has been saved in the database) would look like:

    <select id="whatever" name="whatever">
      <option value="1">First Page</option>
      <option value="2">Second Page</option>
      <option value="3" selected="selected">Third Page</option>
      <option value="4">Fourth Page</option>
    </select>
    

    WordPress has a helper1 function that makes this easier, inside a for/foreach loop you can use:

    <?php selected($value_in_database, $value_of_this_option); ?>
    

    That code outputs the selected="selected" for you if it’s required.