Wordpress WP-add_filter()不从gutenberg块回调传递值
我为Alpine.js制作了一个小过滤器,它将在body元素中呈现一个包装器。 在其中,我想根据(古腾堡)块的输入设置Wordpress WP-add_filter()不从gutenberg块回调传递值,wordpress,filter,wordpress-theming,hook,wordpress-gutenberg,Wordpress,Filter,Wordpress Theming,Hook,Wordpress Gutenberg,我为Alpine.js制作了一个小过滤器,它将在body元素中呈现一个包装器。 在其中,我想根据(古腾堡)块的输入设置x-data属性 这是我当前的代码: 通过硬编码属性值简化回调 如果我将add_过滤器与add_操作s放在同一个文件中,代码就会工作 我假设模板\u重定向是在呈现/处理帖子内容之前运行的 functions.php add_action( "template_redirect", function() { add_action('wp_body_
x-data
属性
这是我当前的代码:
- 通过硬编码属性值简化回调
- 如果我将
与add_过滤器
s放在同一个文件中,代码就会工作add_操作
模板\u重定向
是在呈现/处理帖子内容之前运行的
functions.php
add_action( "template_redirect", function() {
add_action('wp_body_open', function () {
$attributes = apply_filters('alpine_data', []);
$attributes = implode(', ', $attributes);
echo sprintf('<div id="x-data-wrapper" x-data="{%1$s}">',
$attributes
);
});
add_action('wp_footer', function () {
echo '</div>';
});
});
open:false
来自一个块的两个字段。如何将其传递给x-data-wrapper
?
(注意,我制作了一个包装器,因为似乎没有办法向body元素添加属性)
--编辑--
我认为除了javascript之外,没有其他解决方案。
这是我现在的js:
<script >
const wrapper = document.getElementById("x-data-wrapper"); // get element
let attribute = wrapper.getAttribute("x-data"); // get current attribute data
if(attribute){ // if it already has content
attribute = attribute.replace(/\}\s*$/, ""); //remove last bracket
attribute = attribute.concat(", "); // add a devider
} else {
attribute = "{"; // no data? Let's make a new one
}
attribute = attribute.concat("open : false"); // HERE we add the data
attribute = attribute.concat("}"); // sew this patient back up
wrapper.setAttribute("x-data", attribute); // and inject it back
</script>
const wrapper=document.getElementById(“x-data-wrapper”);//获取元素
让attribute=wrapper.getAttribute(“x-data”);//获取当前属性数据
if(attribute){//如果它已经有内容
attribute=attribute.replace(/\}\s*$/,“”)//拆下最后一个支架
attribute=attribute.concat(“,”);//添加一个devider
}否则{
attribute=“{”//没有数据?让我们创建一个新的
}
attribute=attribute.concat(“open:false”);//这里我们添加数据
attribute=attribute.concat(“}”);//把这个病人缝合起来
wrapper.setAttribute(“x-data”,attribute);//然后注射回去
我想我现在就用这个。如果有人有什么建议,请告诉我
<script >
const wrapper = document.getElementById("x-data-wrapper"); // get element
let attribute = wrapper.getAttribute("x-data"); // get current attribute data
if(attribute){ // if it already has content
attribute = attribute.replace(/\}\s*$/, ""); //remove last bracket
attribute = attribute.concat(", "); // add a devider
} else {
attribute = "{"; // no data? Let's make a new one
}
attribute = attribute.concat("open : false"); // HERE we add the data
attribute = attribute.concat("}"); // sew this patient back up
wrapper.setAttribute("x-data", attribute); // and inject it back
</script>