简体   繁体   中英

<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.

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>';}

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 helper 1 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM