我知道有几个帖子是关于这个话题的。我已经关注了其中的许多内容以及网络上的其他资源,并认为我已经记下来了,但它似乎没有起作用。在我的例子中,有两个函数连接到两个需要相同数据的单独操作。
$data = array(\'red\', \'green\', \'blue\');
do_action(\'use_colors_here\', $data);
add_action(\'wp_body_open\', \'use_colors_here\', 10, 1);
function use_colors_here($data) {
$out = \'<h1>Colors</h1>\';
$out .= \'<p>Color 1: \' . $data[1] . \'</p>\';
$out .= \'<p>Color 2: \' . $data[2] . \'</p>\';
echo $out;
}
do_action(\'use_colors_there\', $data);
add_action(\'wp_enqueue_scripts\', \'use_colors_there\', 10, 1);
function use_colors_there($data) {
wp_enqueue_script(\'color-script-1\', get_stylesheet_directory_uri() . \'/js/colors_\' . $data[1] . \'.js\');
wp_enqueue_script(\'color-script-2\', get_stylesheet_directory_uri() . \'/js/colors_\' . $data[2] . \'.js\');
}
预期的行为用于的值$data[1]
和$data[2]
(分别为绿色和蓝色)可由两个功能访问并打印在标记中,每个功能负责添加到页面中。不幸地$data
无法在函数中访问,我最终得到如下标记:<h1>Colors</h1>
<p>Color 1: </p>
<p>Color 2: </p>
我做错了什么?更新仔细阅读后,我发现必须使用钩子而不是函数名作为的第一个参数do_action
. 所以我把它改成:
do_action(\'wp_body_open\', $data);
它似乎正在发挥作用。最终代码(使用接受的答案)
function get_component_config() {
return [\'red\', \'green\', \'blue\'];
}
add_action(\'wp_body_open\', \'use_colors_here\');
function use_colors_here() {
$data = get_component_config();
$out = \'<h1>Colors</h1>\';
$out .= \'<p>Color 1: \' . $data[1] . \'</p>\';
$out .= \'<p>Color 2: \' . $data[2] . \'</p>\';
echo $out;
}
add_action(\'wp_enqueue_scripts\', \'use_colors_there\');
function use_colors_there() {
$data = get_component_config();
wp_enqueue_script(\'color-script-1\', get_stylesheet_directory_uri() . \'/js/colors_\' . $data[1] . \'.js\');
wp_enqueue_script(\'color-script-2\', get_stylesheet_directory_uri() . \'/js/colors_\' . $data[2] . \'.js\');
}