Using WordPress ‘register_block_style_handle()’ PHP function

The register_block_style_handle() WordPress PHP function finds a style handle for the block metadata field. It detects when a path to a file is provided and registers the style under an automatically generated handle name. It returns the unprocessed style handle otherwise.

Usage

register_block_style_handle($metadata, $field_name, $index = 0)

Parameters

  • $metadata (array) – Required. Block metadata.
  • $field_name (string) – Required. Field name to pick from metadata.
  • $index (int) – Optional. Index of the style to register when multiple items are passed. Default is 0.

More information

See WordPress Developer Resources: register_block_style_handle()

Examples

Register a single style handle

In this example, we’ll register a single style handle for a block. We will provide block metadata and a field name.

$metadata = array(
  'style' => 'path/to/style.css'
);
$field_name = 'style';

// Register the style handle
$style_handle = register_block_style_handle($metadata, $field_name);

Register a style handle with a specific index

In this example, we’ll register a style handle for a block with multiple styles. We will provide an index to specify which style to register.

$metadata = array(
  'styles' => array(
    'path/to/style-1.css',
    'path/to/style-2.css'
  )
);
$field_name = 'styles';
$index = 1;

// Register the second style handle
$style_handle = register_block_style_handle($metadata, $field_name, $index);

Register a style handle for a custom field

In this example, we’ll register a style handle for a block with a custom field name.

$metadata = array(
  'my_custom_style' => 'path/to/custom-style.css'
);
$field_name = 'my_custom_style';

// Register the style handle for the custom field
$style_handle = register_block_style_handle($metadata, $field_name);

Register a style handle when the path is not provided

In this example, we’ll attempt to register a style handle when the path to the file is not provided.

$metadata = array(
  'style' => ''
);
$field_name = 'style';

// Attempt to register the style handle
// It will return the unprocessed style handle
$style_handle = register_block_style_handle($metadata, $field_name);

Register a style handle for a block with nested metadata

In this example, we’ll register a style handle for a block with nested metadata.

$metadata = array(
  'styles' => array(
    array(
      'style' => 'path/to/nested-style.css'
    )
  )
);
$field_name = 'styles.style';

// Register the style handle for the nested metadata
$style_handle = register_block_style_handle($metadata, $field_name);