Using WordPress ‘register_block_type_from_metadata()’ PHP function

The register_block_type_from_metadata() WordPress PHP function registers a block type from the metadata stored in the block.json file.

Usage

register_block_type_from_metadata($file_or_folder, $args = array());

Parameters

  • $file_or_folder (string) – Required. Path to the JSON file with metadata definition for the block or path to the folder where the block.json file is located. If providing the path to a JSON file, the filename must end with block.json.
  • $args (array) – Optional. Array of block type arguments. Accepts any public property of WP_Block_Type. See WP_Block_Type::__construct() for information on accepted arguments.

More information

See WordPress Developer Resources: register_block_type_from_metadata

Examples

Register a block type from metadata

This example demonstrates how to register a block type from the metadata stored in the “my-block/block.json” file.

add_action('init', 'my_block_register');

function my_block_register() {
  register_block_type_from_metadata(__DIR__ . '/my-block');
}

Register a block type with custom arguments

This example shows how to register a block type from metadata with custom arguments.

add_action('init', 'my_block_with_args_register');

function my_block_with_args_register() {
  register_block_type_from_metadata(
    __DIR__ . '/my-block',
    array(
      'render_callback' => 'my_custom_render_callback'
    )
  );
}

function my_custom_render_callback() {
  // Custom rendering logic
}

Register multiple block types from different folders

This example demonstrates how to register multiple block types from different folders.

add_action('init', 'register_multiple_blocks');

function register_multiple_blocks() {
  register_block_type_from_metadata(__DIR__ . '/my-first-block');
  register_block_type_from_metadata(__DIR__ . '/my-second-block');
}

Override block.json settings using $args parameter

This example shows how to override specific settings from the block.json file using the $args parameter.

add_action('init', 'override_block_json_settings');

function override_block_json_settings() {
  register_block_type_from_metadata(
    __DIR__ . '/my-block',
    array(
      'title' => 'My Custom Title',
      'category' => 'my-custom-category',
      'icon' => 'dashicons-star'
    )
  );
}

Accessing block attributes in a render callback

This example demonstrates how to access block attributes within a custom render callback.

add_action('init', 'register_block_with_render_callback');

function register_block_with_render_callback() {
  register_block_type_from_metadata(
    __DIR__ . '/my-block',
    array(
      'render_callback' => 'my_render_callback'
    )
  );
}

function my_render_callback($attributes, $content) {
  // Access block attributes
  $title = $attributes['title'];

  // Custom rendering logic
}