Automattic\WooCommerce\Blocks\Assets
Api::register_script()
Registers a script according to wp_register_script, adding the correct prefix, and additionally loading translations.
When creating script assets, the following rules should be followed:
- All asset handles should have a wc- prefix.
- If the asset handle is for a Block (in editor context) use the -block suffix.
- If the asset handle is for a Block (in frontend context) use the -block-frontend suffix.
- If the asset is for any other script being consumed or enqueued by the blocks plugin, use the wc-blocks- prefix.
Method of the class: Api{}
Hooks from the method
Return
null
. Nothing (null).
Usage
$Api = new Api(); $Api->register_script( $handle, $relative_src, $dependencies, $has_i18n );
- $handle(string) (required)
- Unique name of the script.
- $relative_src(string) (required)
- Relative url for the script to the path from plugin root.
- $dependencies(array)
- An array of registered script handles this script depends on.
Default: empty array - $has_i18n(true|false)
- Whether to add a script translation call to this file.
Default: true
Changelog
Since 2.5.0 | Introduced. |
Api::register_script() Api::register script code WC 9.7.1
public function register_script( $handle, $relative_src, $dependencies = [], $has_i18n = true ) { $script_data = $this->get_script_data( $relative_src, $dependencies ); if ( in_array( $handle, $script_data['dependencies'], true ) ) { if ( wp_get_environment_type() === 'development' ) { $dependencies = array_diff( $script_data['dependencies'], [ $handle ] ); add_action( 'admin_notices', function() use ( $handle ) { echo '<div class="error"><p>'; /* translators: %s file handle name. */ printf( esc_html__( 'Script with handle %s had a dependency on itself which has been removed. This is an indicator that your JS code has a circular dependency that can cause bugs.', 'woocommerce' ), esc_html( $handle ) ); echo '</p></div>'; } ); } else { throw new Exception( sprintf( 'Script with handle %s had a dependency on itself. This is an indicator that your JS code has a circular dependency that can cause bugs.', $handle ) ); } } /** * Filters the list of script dependencies. * * @since 3.0.0 * * @param array $dependencies The list of script dependencies. * @param string $handle The script's handle. * @return array */ $script_dependencies = apply_filters( 'woocommerce_blocks_register_script_dependencies', $script_data['dependencies'], $handle ); wp_register_script( $handle, $script_data['src'], $script_dependencies, $script_data['version'], true ); if ( $has_i18n && function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( $handle, 'woocommerce', $this->package->get_path( 'languages' ) ); wp_set_script_translations( $handle, 'woocommerce', $this->package->get_path( 'i18n/languages' ) ); } }