How to Detect Gutenberg via JavaScript and PHP

Detect Gutenberg via JS and PHP

In the recent updates of my Meta Box extensions Conditional Logic and Show Hide, I have added full support for Gutenberg, which allows developers to toggle a meta box or a field based on page template, post format, categories or custom taxonomies.

In order to perform this task, I need a good way to detect if Gutenberg is active on the current screen. I found that the Gutenberg documentation is too technical and lack of such things. When I view it, I feel I’m reading a reference rather than docs or tutorial.

Anyway, the main question is how to detect Gutenberg with JavaScript and PHP?

Detect Gutenberg via JavaScript

Gutenberg adds a lot of namespace via wp global object. It’s quite obvious to use it to detect Gutenberg. So, I was using the following code:

function isGutenbergActive() {
return typeof wp !== 'undefined' && typeof wp.blocks !== 'undefined';
}

However, I found that checking with wp is not always reliable, especially when you use plugins that also use this object.

There is a better way to detect Gutenberg via JavaScript using the following code:

function isGutenbergActive() {
document.body.classList.contains( 'block-editor-page' );
}

This technique uses body class, where Gutenberg adds its own CSS class block-editor-page. So, only when Gutenberg is active, the class is available.

Detect Gutenberg via PHP

To detect if Gutenberg is active on the current screen via PHP, we can use the current admin screen object. It gives us all the information about the current admin screen, including whether Gutenberg is active or not.

Here is the code:

function is_gutenberg_active() {
return get_current_screen()->is_block_editor();
}

It’s quite easy, isn’t it?

Hopefully, these tips can help you work with Gutenberg easier and faster. If you have a better way to detect Gutenberg via JavaScript or PHP, just let me know in the comments.

Leave a Reply

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

BPF - New WordPress Business Theme - Intro Price $29 ONLY!!! Get it now →