Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like to have a metabox for the user to be able to select from a dropdown list one page from the website. I need to save the user choice, so I can use it later. So, my question is how can I create a metabox that will list all my pages?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You can use wp_dropdown_pages. For example

 add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );

/* Adds a box to the main column on the Post edit screens */
function myplugin_add_custom_box() {
    add_meta_box( 
        'myplugin_sectionid',
        __( 'My Post Section Title', 'myplugin_textdomain' ),
        'myplugin_inner_custom_box',
        'post' 
    );
}

/* Prints the box content */
function myplugin_inner_custom_box( $post ) {

     $dropdown_args = array(
        'post_type'        => 'page'
        'name'             => 'myplugin[page]',
        'sort_column'      => 'menu_order, post_title',
        'echo'             => 1,
    );

         // Use nonce for verification
         wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename');

         //Dropdown of pages
         wp_dropdown_pages( $dropdown_args );
}

See also the Codex on handling metabox data.

share|improve this answer
    
Sorry, I wasn't clear enough. This metabox will be use for a theme and not in a plugin. –  Old Castle Jul 3 '12 at 10:03
    
This will work in functions.php too - but it is recommended to have things like this in a plug-in. –  Stephen Harris Jul 3 '12 at 10:07
    
Last question. How can I retrieve the user choice? –  Old Castle Jul 3 '12 at 10:10
    
Hook onto save_post then (after checking its not a revision, and checking nonce, permissions etc - see example on Codex). Inspect $_POST. In this example $_POST['myplugin']['page'] will hold the ID of the selected page. –  Stephen Harris Jul 3 '12 at 10:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.