Search code examples
phparrayswordpresscustom-post-typemeta-boxes

Wordpress custom metabox, load on posts, pages, and all custom post types?


Im trying to make my custom field load on all posts, pages, and all custom post types that are public.

But i don't know how to combine it.

This is variable that i set to load custom field on post and page

public function vf_add_meta_box( $post_type ) {

    if (in_array( $post_type, $this->post_types )) {
        add_meta_box( 
            $this->option_name,
            $this->metabox_name,
            array( $this, 'meta_box_display' ),
            $post_type,
            'normal',
            'high'
        );
    }
}

$post_type is defined in other function and inserted in __construct and it's set like this

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

And from wordpress codex instructions in order to get all custom post types you can use this code.

$args = array(
   'public'   => true,
   '_builtin' => false
);

$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'

$custom_types = get_post_types( $args, $output, $operator ); 

foreach ( $custom_types  as $post_type ) {

   return $post_type ;
}

So i assumed if i add $post_type to $post_types array

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

it would display metabox in custom post type but it's not working.


Solution

  • Try replacing your last foreach with this:

    $post_types = array_merge($post_types, $custom_types);
    

    That should combine your custom post types array with your default $post_types array.