How to catch Gutenberg

How to know by code which editor is currently used for post editing in site console?

How to catch Gutenberg


The new editor called Gutenberg is here as plugin in 4.9, and as core functionality called Block Editor, in 5.0. Regarding to it, it is often needed to determine programmatically which editor is used to edit post or page in the site console.

There are several variants:

  • WordPress 4.9, Gutenberg plugin is not active
  • WordPress 4.9, Gutenberg plugin is active
  • WordPress 5.0, Block Editor by default
  • WordPress 5.0, Classic Editor plugin is active
  • WordPress 5.0, Classic Editor plugin is active, but in site console in “Settings > Writing” the option “Use the Block editor by default…” is selected

All the mentioned variants can be processed by the following code:

/**
 * Check if Block Editor is active.
 * Must only be used after plugins_loaded action is fired.
 *
 * @return bool
 */
function is_active() {
	// Gutenberg plugin is installed and activated.
	$gutenberg = ! ( false === has_filter( 'replace_editor', 'gutenberg_init' ) );

	// Block editor since 5.0.
	$block_editor = version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' );

	if ( ! $gutenberg && ! $block_editor ) {
		return false;
	}

	if ( is_classic_editor_plugin_active() ) {
		$editor_option       = get_option( 'classic-editor-replace' );
		$block_editor_active = array( 'no-replace', 'block' );

		return in_array( $editor_option, $block_editor_active, true );
	}

	return true;
}

/**
 * Check if Classic Editor plugin is active.
 *
 * @return bool
 */
function is_classic_editor_plugin_active() {
	if ( ! function_exists( 'is_plugin_active' ) ) {
		include_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	if ( is_plugin_active( 'classic-editor/classic-editor.php' ) ) {
		return true;
	}

	return false;
}

Function returns true if block editor is active by any means, and false – in the case if classic editor is here. This function must only be used after plugins_loaded action is fired.

P.S. Due release of version 1.2 of Classic Editor plugin, code is updated, as classic-editor-replace options now takes values not replace and no-replace, but classic and block.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.