我正在创建一个古腾堡动态块。问题是我无法访问 render.php 之外的属性值,即使在我的主要插件 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');`
Here is my block.json code :
`{
"$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)
我尝试重新检查代码。但仍然无法找到为什么主插件文件没有将 $jokescategory 的值连接到控制台。
$jokes_array = ['url'=>'https://api.chucknorris.io/jokes/random?category=' . $jokescategory];
wp_localize_script( 'joke-script', 'joke_value',$jokes_array);
我找不到解决方案已经 5 个小时了,请帮忙!