Check if the current post is using block editor (Gutenberg) or classic editor

WordPress 5+ will use the block editor by default and there is no way to switch to the classic editor using the admin options only. However, developers may disable it using different methods like action hooks for example. Or another option would be to install the Classic Editor plugin.

Either way, this will allow writing posts using the new block editor or classic editor.

But how do we detect which one is in use? And why would you want to detect this?

Let’s first start with the why would you want to detect which one is in use for a particular post.

There are many cases when this may be needed, but the first thing that comes to my mind is that you may want to register a metabox for the block editor, and none for the classic editor. Or maybe you want to have different metaboxes for each editor type.

The block editor does a great job keeping the legacy metaboxes, and having them fully functional in the new block editor. However, sometimes we may not want to show them if it is in use.

How do we detect if the current post is using block editor (aka Gutenberg)?

The current screen object contains this information and allows us to check for it.

function zwp_is_block_editor(){
    $current_screen = get_current_screen();
    return method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor();
}

The above function will return a boolean. When the returned value is true it means that the block editor is used by the current post. When is false, the classic editor of course.

Example: Conditional metabox registration.

Now let’s register a metabox only if the block editor is not in use.


function zwp_register_meta_box() {
    // Register this metabox only if block editor is not in use for the current post
    if (zwp_is_block_editor()){
        return;
    }

    add_meta_box(
        'zwp-metabox-example',
        esc_html__( 'Metabox example title', 'amdm' ),
        'zwp_metabox_callback',
        ['post', 'page'],
        'side',
        'high'
    );
}

add_action( 'add_meta_boxes', 'zwp_register_meta_box' );

Conclusion

Conditional functionality is a must, and detecting the block editor is something that we may want to do for different use cases. It’s easy and it does not require any hack. We’re just using what it’s already built in the core of WordPress.

Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

  • Aaron 2 months ago

    Thanks for sharing, that helped me go in the right direction.

Your email address will not be published.