Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block.json returnes wrong paths

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'
    ) );
like image 810
Jonatanbs Avatar asked Apr 23 '26 06:04

Jonatanbs


1 Answers

Edit (Sept 2023): As of WordPress 6.0, register_block_script_handle "allows registration of blocks that include assets from within a theme."

Refs: https://core.trac.wordpress.org/changeset/53091


Original answer (from Feb 2022):

Block registration uses register_block_script_handle when loading from block.json.

That function uses plugins_url to generate URLs if the script uses the file:<path> pattern.

Passing in an already existing handle (e.g., mycustomblock-js) works because register_block_script_handle sees it's not file:<path> and just uses that handle (and corresponding URL) as-is.

like image 79
edavis Avatar answered Apr 24 '26 22:04

edavis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!