I’ve created a custom block plugin with @wordpress/create-block (https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/)
It works as a plugin, but when i move it into the theme, the "editorScript" in the block.json file, returns the wrong path.
themeDirectory/blocks/mycustomblock/block.json
{
"name": "create-block/mycustomblock",
"title": "Mycustomblock",
"description": "Example block written with ESNext standard and JSX support – build step required.",
"category": "text",
"icon": "smiley",
"supports": {
"html": false
},
"attributes":{
"backgroundColor": {
"type": "string",
"default": "red"
}
},
"editorScript": "file:./build/index.js"
}
Returned path from editorScript:
404 | http://localhost:8888/wordpress-test/wp-content/plugins/Users/jonrose/Dropbox/htdocs/wordpress-test/wp-content/themes/mytheme/blocks/mycustomblock/build/index.js?ver=4f45658ee3212a45c5d5367f6fbdfeba
If i register the script inside the register_block_type function it works fine
wp_register_script( 'mycustomblock-js', get_template_directory_uri() . '/blocks/mycustomblock/build/index.js', array( 'wp-blocks' ));
register_block_type( __DIR__, array(
'editor_script' => 'mycustomblock-js'
) );
2
Answers
Registering a block type with
block.json
usesregister_block_script_handle
under the hood to register all relevant block scripts. That function usesplugins_url
to generate URLs if the script uses thefile:<path>
pattern.Passing in an already existing handle (e.g.,
mycustomblock-js
) works becauseregister_block_script_handle
sees it’s notfile:<path>
and just uses that handle (and corresponding URL) as-is.edavis is correct and that
plugins_url()
method is called when enqueing theeditorScript
,editorStyle
, andstyle
paths.Although you can pass other arguments to
register_block_type
to declare what you need I do like the idea of just keeping a simpleblock.json
file. To make this work within a theme I used a filter hook forplugins_url
to fix up the URL if it detects the theme path is included in the URL.