WordPress Gutenberg动态块PHP变量无法在JS控制台输出求助
WordPress Gutenberg动态块:无法在render.php外访问块属性值
我正在开发一个WordPress Gutenberg动态块,目前遇到的问题是无法在render.php之外(包括主插件文件random-jokes.php)访问块属性值,控制台输出的URL没有正确拼接$jokescategory的值。排查了5小时仍未解决,相关代码如下:
主插件文件random-jokes.php代码
<?php /** * Plugin Name: Random Jokes * Description: Example block scaffolded with Create Block tool. * Requires at least: 6.1 * Requires PHP: 7.0 * Version: 0.1.0 * Author: The WordPress Contributors * License: GPL-2.0-or-later * License URI: https://www.gnu.org/licenses/gpl-2.0.html * Text Domain: random-jokes * * @package create-block */ /** * Registers the block using the metadata loaded from the `block.json` file. * Behind the scenes, it registers also all assets so they can be enqueued * through the block editor in the corresponding context. * * @see https://developer.wordpress.org/reference/functions/register_block_type/ */ function create_block_random_jokes_block_init() { register_block_type( __DIR__ . '/build' ); } add_action( 'init', 'create_block_random_jokes_block_init' ); //setup function Joke_block_value(){ global $jokescategory; $jokes_array = ['url'=>'https://api.chucknorris.io/jokes/random?category=' . $jokescategory]; wp_register_script( 'joke-script', plugin_dir_url( __FILE__ ).'/build/scripts.js', array(), '1.90.0',true); wp_enqueue_script('joke-script'); wp_localize_script( 'joke-script', 'joke_value',$jokes_array); } add_action( 'wp_enqueue_scripts','Joke_block_value');
block.json代码
{ "$schema": "https://schemas.wp.org/trunk/block.json", "apiVersion": 2, "name": "create-block/random-jokes", "version": "0.1.0", "title": "Random Jokes", "category": "widgets", "icon": "smiley", "description": "Example block scaffolded with Create Block tool.", "supports": { "html": false }, "attributes": { "joke":{"type":"string"}, "category":{ "type":"string", "default":"food" } }, "textdomain": "random-jokes", "editorScript": "file:./index.js", "viewScript":"file:./scripts.js", "editorStyle": "file:./index.css", "style": "file:./style-index.css", "render": "file:./render.php" }
render.php代码
<div <?php echo get_block_wrapper_attributes(); global $jokescategory; $jokescategory = $attributes['category']; ?>> <p id="joke"> <?php echo $jokescategory?></p> </div>
scripts.js代码
console.log(joke_value)
问题根源
- 执行顺序错误:
wp_enqueue_scripts钩子的触发早于块的render.php渲染逻辑,导致Joke_block_value()函数执行时,全局变量$jokescategory还未被赋值,最终URL拼接结果为空。 - 全局变量不适用于多实例场景:如果页面存在多个该块,全局变量会被最后一个块的属性值覆盖,所有块将共享同一个分类值。
解决方案
方案1:直接在render.php中传递属性给JS(简单高效)
不需要通过主插件文件中转,直接在块的渲染模板里将属性输出给前端:
修改render.php:
<div <?php echo get_block_wrapper_attributes(); ?>> <p id="joke"> <?php echo esc_html( $attributes['category'] ); ?> </p> <script> // 直接获取当前块的分类并生成URL const jokeUrl = `https://api.chucknorris.io/jokes/random?category=<?php echo esc_js( $attributes['category'] ); ?>`; console.log(jokeUrl); </script> </div>
同时删除主插件文件中的Joke_block_value()函数及对应的wp_enqueue_scripts钩子,不再需要wp_localize_script传递值。
方案2:通过DOM属性传递属性给独立viewScript(规范Gutenberg写法)
如果需要保持前端脚本的独立性,可通过DOM自定义属性存储块属性,再由viewScript读取:
- 修改
render.php,给块容器添加自定义属性:
<div <?php echo get_block_wrapper_attributes( array( 'data-joke-category' => esc_attr( $attributes['category'] ), ) ); ?>> <p id="joke"> <?php echo esc_html( $attributes['category'] ); ?> </p> </div>
- 修改
scripts.js,从DOM中读取属性并生成URL:
// 遍历页面中所有该类型的块 document.querySelectorAll('.wp-block-create-block-random-jokes').forEach(block => { const category = block.dataset.jokeCategory; const jokeUrl = `https://api.chucknorris.io/jokes/random?category=${category}`; console.log(jokeUrl); // 这里可添加API请求逻辑 });
- 删除主插件文件中的
Joke_block_value()函数及对应钩子,无需再通过全局变量传递值。
内容的提问来源于stack exchange,提问作者rawaha johns
相关产品推荐
相关产品推荐

