I am trying to create some function for metaboxes and some reason i can't get get_post_type
to work in in_array
.
Everything else seems to work in testing but in_array nope.
This is the function that i have
$metabox = array(
'metabox_one' => array(
'title' => 'First',
'screen' => array( 'post' )
),
'metabox_two' => array(
'title' => 'Second',
'screen' => array( 'post', 'page')
)
);
So for each of those keys in array i want to check screen
value and if it's in that array to display metabox.
function call_vivid_framework_metaboxClass() {
$post_type = get_post_type();
if( isset($metabox) ) {
foreach ( $metabox as $key => $value ) {
if ( in_array( $post_type, $value['screen'] )) {
new vivid_framework_metaboxClass( $key, $value );
}
}
}
}
add_action( 'load-post.php', 'call_vivid_framework_metaboxClass' );
add_action( 'load-post-new.php', 'call_vivid_framework_metaboxClass' );
And this is when it fails and basically don't display any metabox as it doesn't exist in the array.
When i try to print $value['screen']
i get an array
[0] => post,
[1] => page
When i try to print $post_type
on a new page i get an page
but still it fails in_array
When i try to manually set an array instead $value['screen']
as:
$screen = array( 'post', 'page');
It fails again.
And when i try to manually set post type in in_array
than it works as:
in_array('page', $value['screen'])
It loads metabox within that $value
array.
The only thing that comes to my min is that my function hook is fired before get_post_type() so it doesn't catch the value of post type.
For the class i used and example from WordPress codex page https://codex.wordpress.org/Function_Reference/add_meta_box#Class
Any ideas or suggestion how to get it to work ?
metabox_one
andmetabox_two
aren't valid array keys - they should be in quotes. Where is theforeach
loop you describe? Is your call toget_post_type()
returning something that's notfalse
? Is the constructor ofclass vivid_framework_metaboxClass
actually coded to produce markup? What "function hook" are you suspecting of firing beforeget_post_type()
?in_array( $post_type, $value['screen'] )
combination. I already saidget_post_type()
returns 'page' the consturctor of class works good it shows and saves everything as it should. and metabox keys is just a typo here in post. foreach loop is activated inside function which is called byadd_action( 'load-post.php', 'call_vivid_framework_metaboxClass' );
I did made a workaround by using in_array in class constructor instead a function but i am still curious why it doesn't work inside function here.