Dropdown list of pages to get page id to store in plugin options

Iam using following code to display a page select dropdown menu on an plugin option page.

If you select an page and save it, the next time you visit the option-site, you will also see which page was saved. (so no more “select page”)

You can use the WordPress selected() function, you can find more details here:
https://codex.wordpress.org/Function_Reference/selected

$options = get_option( 'my_settings' ); ?>

<select name="my_settings[selected_page]">
    <option value="0"><?php _e('Select a Page', 'textdomain'); ?></option>
    <?php $pages = get_pages(); ?>
    <?php foreach( $pages as $page ) { ?>
        <option value="<?php echo $page->ID; ?>" <?php selected( $options['selected_page'], $page->ID ); ?> ><?php echo $page->post_title; ?></option>
    <?php }; ?>
</select>

You just need to get the current-saved-value of the field and than use the WP selected() function to compare the current-saved-value with the $page->ID.

Maybe this can help you.

Leave a Comment