1

I am currently developing a plugin inside the admin page and I need to have a drop down list, listing all the pages. I need to be able to select one page and save the "ID" as an option. I am currently using this:

<select name="easyreg_redirect_page"> 
    <option value=""><?php echo esc_attr( __( 'Select page' ) ); ?></option> 
    <?php 
        $pages = get_pages(); 
        foreach ( $pages as $page ) {
            $option = '<option value="' . $page->ID . '">';
            $option .= $page->post_title;
            $option .= '</option>';
            echo $option;
        }
    ?>
</select>

My 2 problems are:

1 - I would like the "Select Page" to always be available with an empty value (and I will make a check that it cannot be selected but this is an other story ;-) )

2 - When I come back to my plugin Admin page I would like to see the page name that is currently saved in the options, neither and empty line nor the "Select Page".

1
  1. You already have <option value="">...</option> you just need some extra attrs for it
  2. You need to load current value and if value equals $page->ID than add attr selected="selected"

Here's how it could be done:

<select name="easyreg_redirect_page"> 
    <option selected="selected" disabled="disabled" value=""><?php echo esc_attr( __( 'Select page' ) ); ?></option> 
    <?php
        $selected_page = get_option( 'option_key' );
        $pages = get_pages(); 
        foreach ( $pages as $page ) {
            $option = '<option value="' . $page->ID . '" ';
            $option .= ( $page->ID == $selected_page ) ? 'selected="selected"' : '';
            $option .= '>';
            $option .= $page->post_title;
            $option .= '</option>';
            echo $option;
        }
    ?>
</select>

where's option_key you should enter options key where your value can be found ( where it saves it )

also, you could use wordpress selected function to write selected="selected", then it would be like these:

$option = '<option value="' . $page-ID . '" ' . selected( $selected_page, $page->ID ) . '>';
  • Thanks a lot Maikal... Exactly what I was looking for. I was just missing how to get the selected! I guess my programming is slowly getting there ;-) hehe Thanks a lot for your time!! – pSyToR Jan 23 '15 at 3:08

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.