Enable or Disable Blocks by Post Type
- This topic has 7 replies, 2 voices, and was last updated 4 years ago by
Chicharito.
-
AuthorPosts
-
April 1, 2021 at 2:44 AM #26843
Chicharito
ParticipantIs 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.April 1, 2021 at 9:46 AM #26854Long Nguyen
ModeratorHi,
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; }
April 2, 2021 at 12:14 AM #26884Chicharito
ParticipantThat worked perfectly.
Thanks!April 2, 2021 at 1:42 AM #26886Chicharito
ParticipantSpoke too soon, I thought it was working but it seems that at that point
get_post_type
is always false.April 2, 2021 at 10:29 AM #26896Long Nguyen
ModeratorHi,
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; }
April 2, 2021 at 11:32 PM #26918Chicharito
ParticipantIt 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.April 3, 2021 at 2:57 PM #26929Long Nguyen
ModeratorHi,
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; }
April 9, 2021 at 12:43 AM #27067Chicharito
ParticipantSince 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.
-
AuthorPosts
- You must be logged in to reply to this topic.