Support Forum
Is there a way to enable or disable blocks by post type?
Something similar to
'post_types' => 'my_post_type',
But for blocks.
I tried it but it doesn't work.
Hi,
You can check the post type with the function get_post_type() before registering the meta box. For example:
function your_prefix_function_name( $meta_boxes ) {
if( 'my_post_type' == get_post_type() ) {
return;
}
$meta_boxes[] = [
...
];
return $meta_boxes;
}
That worked perfectly.
Thanks!
Spoke too soon, I thought it was working but it seems that at that point
get_post_type
is always false.
Hi,
Please try again with this code.
function your_prefix_function_name( $meta_boxes ) {
if( isset( $_GET['post_type'] ) && $_GET['post_type'] == 'my_post_type' ) {
return;
}
$meta_boxes[] = [
...
];
return $meta_boxes;
}
It didn't work, but I tried this
global $pagenow;
if ( 'post.php' === $pagenow && isset( $_GET['post'] ) ) {
$post_id = $_GET['post'];
$post = get_post( $post_id );
$post_type = $post->post_type;
if ( 'page' === $post_type ) {
return;
}
}
I can get the post type, but when it hits return none of my blocks work.
I get this message on all of the blocks:
Your site doesn’t include support for the "meta-box/my-block" block. You can leave this block intact or remove it entirely.
Hi,
The code helps you to disable one custom block on the specific post type, understand that is enabled by default if you do not add the condition. See my screen record https://share.getcloudapp.com/L1udYD40.
Full of code to test
add_filter( 'rwmb_meta_boxes', 'your_prefix_function_name', 999 );
function your_prefix_function_name( $meta_boxes ) {
$prefix = '';
if( isset( $_GET['post_type'] ) && $_GET['post_type'] == 'page' ) {
return $meta_boxes;
}
$meta_boxes[] = [
'title' => __( 'My Block', 'your-text-domain' ),
'category' => 'text',
'type' => 'block',
'context' => 'content',
'fields' => [
[
'name' => __( 'Text', 'your-text-domain' ),
'id' => $prefix . 'text_t4541bur58',
'type' => 'text',
],
],
];
return $meta_boxes;
}
Since I have separate archives for each block, my solution was to load the block file based on the post type. It may not be the best solution but it is working.