Creating a Custom Post Types dropdown in a Meta Box

Of course it is possible.

Below is code that will display registered post types:

function my_meta_box_add() {
    add_meta_box( 'my-meta-box-id', 'MY meta', 'my_meta_box', 'page', 'normal', 'high' );
} add_action( 'add_meta_boxes', 'my_meta_box_add' );


function my_meta_box( $post ) {
    ?>
    <p>
        <label for="my_meta_box_post_type">Post type: </label>
        <select name="my_meta_box_post_type" id='my_meta_box_post_type'>
            <?php $post_types=get_post_types('', 'objects'); foreach ($post_types as $post_type): ?>
            <option value="<?php echo esc_attr($post_type->name); ?>"><?php echo esc_html($post_type->name); ?></option>
            <?php endforeach; ?>
        </select>
    </p>
    <?php   
}

Of course you have to take care of saving this value, checking nonces, and so on.

Leave a Comment