我使用@wordpress/create-block创建了一个自定义块插件(https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/)
它作为一个插件工作,但是当我将它移动到主题中时,block.json 文件中的“editorScript”返回错误的路径。
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"
}
从编辑器脚本返回的路径:
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
如果我在 register_block_type 函数中注册脚本,它就可以正常工作
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'
) );
编辑(2023 年 9 月): 从 WordPress 6.0 开始,
register_block_script_handle
可以更好地包含主题内的资源。现在应该“正常工作”了。
https://core.trac.wordpress.org/changeset/53091
原答案:
使用
block.json
注册块类型会在后台使用 register_block_script_handle
来注册所有相关的块脚本。 如果脚本使用 plugins_url
模式,该函数将使用 file:<path>
生成 URL。
传入一个已经存在的句柄(例如,
mycustomblock-js
)是有效的,因为register_block_script_handle
看到它不是file:<path>
并且只按原样使用该句柄(和相应的URL)。
edavis 是正确的,并且在对
plugins_url()
、editorScript
和 editorStyle
路径进行排队时调用 style
方法。
虽然您可以将其他参数传递给
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 );