if is gutenberg page php wp
<?php
if ( function_exists( 'register_block_type' ) ) {
function my_gutenberg_custom_block() {
wp_register_script(
'my-gutenberg-block',
plugins_url( 'my-block.js', __FILE__ ),
array( 'wp-blocks', 'wp-editor', 'wp-components' )
);
register_block_type( 'my-plugin/my-custom-block', array(
'editor_script' => 'my-gutenberg-block',
) );
}
add_action( 'init', 'my_gutenberg_custom_block' );
}
Explanation:
This code checks if the Gutenberg editor is available in the WordPress environment by verifying the existence of the register_block_type
function. If it's present, it defines a custom block for the Gutenberg editor.
if ( function_exists( 'register_block_type' ) ) { ... }
: This conditional statement checks if theregister_block_type
function exists in the current WordPress environment.function my_gutenberg_custom_block() { ... }
: Defines a function calledmy_gutenberg_custom_block()
that registers a custom block.wp_register_script( ... )
: Registers a JavaScript file (my-block.js
) as a script for the custom block. This file contains the necessary functionalities for the custom Gutenberg block.plugins_url( 'my-block.js', __FILE__ )
: Retrieves the URL for the JavaScript filemy-block.js
within the current plugin or theme directory.array( 'wp-blocks', 'wp-editor', 'wp-components' )
: Denotes the dependencies for the script. In this case, it requires thewp-blocks
,wp-editor
, andwp-components
scripts to be loaded before.register_block_type( 'my-plugin/my-custom-block', ... )
: Registers a new custom block type with the identifier'my-plugin/my-custom-block'
.array( 'editor_script' => 'my-gutenberg-block' )
: Associates the previously registered script (my-gutenberg-block
) with the custom block type to enable its functionality within the Gutenberg editor.add_action( 'init', 'my_gutenberg_custom_block' );
: Hooks themy_gutenberg_custom_block()
function to the WordPressinit
action, ensuring that the custom block is initialized during the WordPress loading process when theinit
action is triggered.