I’m building a metabox gallery in WordPress for a specific page template. I have the following warning notice in the dashboard:
Warning: in_array() expects parameter 2 to be array, null given in…
The warning is for the code line: if ( in_array( $post_type, $post_types ) ) {
public function add_meta_box( $post_type ) {
$post_types = apply_filters( 'sortable_wordpress_gallery_post_types', array( 'post' ) );
$post_types = apply_filters( 'sortable_wordpress_gallery_' . $this->id . '_post_types', $post_types );
if ( in_array( $post_type, $post_types ) ) {
add_meta_box(
$this->id,
$this->title,
array( $this, 'render_meta_box_content' ),
$post_type,
$this->context,
$this->priority
);
}
}
This is the code where I specify the page template where the metabox should be displayed.
add_filter( 'sortable_wordpress_gallery_post-metabox_post_types', 'first_gallery_only_on_page' );
function first_gallery_only_on_page( $post_types ) {
global $post;
if(!empty($post)) {
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-coworking.php' ) {
return array( 'page' );
}
}
}
I understand that one of my param is null, but I don’t find the way to set it before using it. Thank you.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Well first you have this code
// no matter what the value here, you can forget about it (because in the next line of code you assing a new value to the same variable) $post_types = apply_filters( 'sortable_wordpress_gallery_post_types', array( 'post' ) ); // only this really matters $post_types = apply_filters( 'sortable_wordpress_gallery_' . $this->id . '_post_types', $post_types );
The value in the second $post_types is what you check.
Now the callback function
You do a check if $post is empty, do some code and return an array. But you forgot to return a value if $post is not empty.
In fillters the first parameter of the callback function is returned, so in this case right before the closing bracket of the callback function you need to return $post_types
Complete example for callback function
function first_gallery_only_on_page ($post_types) {
global $post;
if (!empty($post)) {
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if ($pageTemplate == 'page-coworking.php' ) {
return array( 'page' );
}
}
return $post_types; // add this line
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0