Amit

How to create custom Gutenberg blocks in WordPress.

Follow the steps below on how to create Gutenberg block with code:

  1. Register Assets & Block Type

Note: if you need to design edit-block on dashboard. create block-admin.css and must use “wp-editor-block” in array format.

add_action( 'init', 'ab_register_gutenberg_block_type' );

function ab_register_gutenberg_block_type() {
  // Check if Gutenberg is not active
  if ( !function_exists( 'register_block_type' ) ) {
    return;
  }

  // Register custom CSS and JS directory
  $css_dir = get_stylesheet_directory_uri() . '/blocks/css';
  $js_dir = get_stylesheet_directory_uri() . '/blocks/js';

  //for admin css two array required
  wp_register_script( 
  	'ab-block-admin', 
  	$js_dir . '/ab-block-editor.js', 
  	array( 'wp-blocks', 'wp-element' )
  );
  // for admin css one array required
  wp_register_style( 
  	'ab-block-admin', 
  	$css_dir . '/ab-block-admin.css', 
  	array( 'wp-edit-blocks')
  );
  // for admin and frontend no array required
  wp_register_style( 'ab-block',
   $css_dir . '/ab-block.css'
   	array()
    );

  // Register block type and enqueue the js and css.
  register_block_type( 'my/simple-text', [
    'editor_style' => 'ab-block-admin',  // add js file admin only
    'editor_script' => 'ab-block-admin', // add css file admin only
    'style' => 'ab-block',               // admin css file admin & public
  ] );
}

2. The Basic Script

The snippet below is a starting point for creating a custom block:

Note: create a ab-block-editor.js file in the js folder.

( function( blocks, element, blockEditor ) {
  var el = element.createElement;
  var RichText = blockEditor.RichText;

  blocks.registerBlockType( 'ab/simple-text', {
    title: 'Amit Bera',
    icon: 'universal-access-alt',
    category: 'layout',
    example: {},

    // All the children inside 'p' will be extracted as 'text' variable.
    attributes: {
      text: { type: 'array', source: 'children', selector: 'p' }
    },
    edit: abEdit,
    save: abSave,
  } );

  // Render RichText (field with basic toolbar) wrapped with 'p'
  function abEdit( props ) {
    return el( RichText, {
      tagName: 'p',
      onChange: _onChange,
      value: props.attributes.text,
      className: props.className,
    } );
    
    // when changed, update the attribute
    function _onChange( newContent ) {
      props.setAttributes( { text: newContent } );
    }
  }
  
  // Save the content of RichText wrapped with 'p'
  function abSave( props ) {
    return el( RichText.Content, {
      tagName: 'p',
      className: props.className,
      value: props.attributes.text,
    } );
  }
  
}( window.wp.blocks, window.wp.element, window.wp.blockEditor ) ); 

Last Update on:March 5th, 2023 at 5:19 pm


WordPress pagination for custom post type without plugin
Previous post