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:
WordPress has a helper1 function that makes this easier, inside a for/foreach loop you can use:
That code outputs the
selected="selected"
for you if it’s required.