6

I have this code

function add_custom_meta_box() {
add_meta_box(
    'custom_meta_box', // $id
    'Custom Meta Box', // $title 
    'show_custom_meta_box', // $callback
     'page', // $page    
    'normal', // $context
    'high'); // $priority
}
add_action('add_meta_boxes', 'add_custom_meta_box');

I want to add more post type like page,post,custom_post_type in this code

  'page', // $page 

How should I rewrite my code?

2 Answers 2

10

Define an array of post types, and register the metabox for each one separately:

function add_custom_meta_box() {

    $post_types = array ( 'post', 'page', 'event' );

    foreach( $post_types as $post_type )
    {
        add_meta_box(
            'custom_meta_box', // $id
            'Custom Meta Box', // $title 
            'show_custom_meta_box', // $callback
             $post_type,
            'normal', // $context
            'high' // $priority
        );
    }
}
3
  • 3
    get_post_types could be used to automate the process.
    – brasofilo
    Commented Nov 24, 2012 at 15:19
  • @brasofilo If I remember that correctly, passing NULL as post type would catch all. But have never done that. Unpredictable results.
    – fuxia
    Commented Nov 24, 2012 at 15:35
  • 1
    My first comment should had a question mark... But, just tested this and works fine: $post_types=get_post_types(array('public'=>true,'_builtin'=>false)); array_push($post_types,'post','page');
    – brasofilo
    Commented Nov 24, 2012 at 15:47
4

If your aim is to add all post types, then you can get the array of post types with:

$post_types = get_post_types( array('public' => true) );

Or add an argument for WP core post types or custom ones:

// only WP core post types
$post_types = get_post_types( array('public' => true, '_builtin' =>‌ true) );

// only custom post types
$post_types = get_post_types( array('public' => true, '_builtin' =>‌ false) );

Use it like this:

add_meta_box(
    'custom_meta_box', // $id
    'Custom Meta Box', // $title 
    'show_custom_meta_box', // $callback
     $post_types,
    'normal', // $context
    'high' // $priority
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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