wpseek.com
A WordPress-centric search engine for devs and theme authors



register_block_script_handle › WordPress Function

Since5.5.0
Deprecatedn/a
register_block_script_handle ( $metadata, $field_name )
Parameters: (2)
  • (array) $metadata Block metadata.
    Required: Yes
  • (string) $field_name Field name to pick from metadata.
    Required: Yes
Returns:
  • (string|false) Script handle provided directly or created through script's registration, or false on failure.
Defined at:
Codex:

Finds a script handle for the selected block metadata field. It detects when a path to file was provided and finds a corresponding asset file with details necessary to register the script under automatically generated handle name. It returns unprocessed script handle otherwise.



Source

function register_block_script_handle( $metadata, $field_name ) {
	if ( empty( $metadata[ $field_name ] ) ) {
		return false;
	}
	$script_handle = $metadata[ $field_name ];
	$script_path   = remove_block_asset_path_prefix( $metadata[ $field_name ] );
	if ( $script_handle === $script_path ) {
		return $script_handle;
	}

	$script_handle     = generate_block_asset_handle( $metadata['name'], $field_name );
	$script_asset_path = realpath(
		dirname( $metadata['file'] ) . '/' .
		substr_replace( $script_path, '.asset.php', - strlen( '.js' ) )
	);
	if ( ! file_exists( $script_asset_path ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: Field name, 2: Block name. */
				__( 'The asset file for the "%1$s" defined in "%2$s" block definition is missing.' ),
				$field_name,
				$metadata['name']
			),
			'5.5.0'
		);
		return false;
	}
	$is_core_block       = isset( $metadata['file'] ) && 0 === strpos( $metadata['file'], ABSPATH . WPINC );
	$script_uri          = $is_core_block ?
		includes_url( str_replace( ABSPATH . WPINC, '', realpath( dirname( $metadata['file'] ) . '/' . $script_path ) ) ) :
		plugins_url( $script_path, $metadata['file'] );
	$script_asset        = require $script_asset_path;
	$script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array();
	$result              = wp_register_script(
		$script_handle,
		$script_uri,
		$script_dependencies,
		isset( $script_asset['version'] ) ? $script_asset['version'] : false
	);
	if ( ! $result ) {
		return false;
	}

	if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies ) ) {
		wp_set_script_translations( $script_handle, $metadata['textdomain'] );
	}

	return $script_handle;
}