Jon*_*nbs 10 php wordpress wordpress-gutenberg gutenberg-blocks
我使用 @wordpress/create-block 创建了一个自定义块插件(https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/)
\n它作为一个插件工作,但是当我将它移动到主题中时,block.json 文件中的“editorScript”返回错误的路径。
\nthemeDirectory/blocks/mycustomblock/block.json\n\n{\n    "name": "create-block/mycustomblock",\n    "title": "Mycustomblock",\n    "description": "Example block written with ESNext standard and JSX support \xe2\x80\x93 build step required.",\n    "category": "text",\n    "icon": "smiley",\n    "supports": {\n        "html": false\n    },\n    "attributes":{\n        "backgroundColor": {\n            "type": "string",\n            "default": "red"\n        }\n    },\n    "editorScript": "file:./build/index.js"\n}\nRun Code Online (Sandbox Code Playgroud)\n从 editorScript 返回的路径:
\n404 | 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\nRun Code Online (Sandbox Code Playgroud)\n如果我在 register_block_type 函数中注册脚本,它可以正常工作
\nwp_register_script( \'mycustomblock-js\', get_template_directory_uri() . \'/blocks/mycustomblock/build/index.js\', array( \'wp-blocks\' ));\n\n    register_block_type( __DIR__, array(\n        \'editor_script\' => \'mycustomblock-js\'\n    ) );\nRun Code Online (Sandbox Code Playgroud)\n
    编辑(2023 年 9 月):从 WordPress 6.0 开始,register_block_script_handle“允许注册包含主题内资产的块。”
参考文献: https: //core.trac.wordpress.org/changeset/53091
原始答案(2022 年 2 月起):
register_block_script_handle从 加载时阻止注册使用block.json。
plugins_url如果脚本使用该模式,该函数将用于生成 URL file:<path>。
传入一个已经存在的句柄(例如,mycustomblock-js)是有效的,因为register_block_script_handle它不是file:<path>,并且只是按原样使用该句柄(和相应的 URL)。
edavis 是正确的,并且在对、和路径plugins_url()进行排队时调用该方法。editorScripteditorStylestyle
尽管您可以传递其他参数来register_block_type声明您需要什么,但我确实喜欢只保留一个简单文件的想法block.json。为了在主题中实现此功能,我使用了一个过滤器挂钩来plugins_url修复 URL(如果它检测到主题路径包含在 URL 中)。
add_filter( 'plugins_url', function ( $url, $path, $plugin ) {
    if ( strpos( $url, get_template_directory() ) !== false ) {
        $url = str_replace( 'wp-content/plugins' . get_home_path(), '', $url );
    }
    return $url;
}, 10, 3 );
Run Code Online (Sandbox Code Playgroud)