gpt4 book ai didi

javascript - 如何在 wordpress 短代码中添加内联 css/js

转载 作者:行者123 更新时间:2023-11-28 05:22:57 25 4
gpt4 key购买 nike

我正在努力创建一个短代码,旨在根据情况动态更改该短代码的 css 和 js。现在的问题是我不知道如何在 add_shortcode() 中使用 add_action()。让我给你一个示例代码片段,以便你们更好地理解我:

add_shortcode('example', function( $atts ) {
//extracting the shortcode attributes
extract( shortcode_atts( array(
'value1' => null,
'value2' => null,
'value3' => null
), $atts ) );

//Now here I wll do my code for the shortcode
// But the shortcode needs some js and css to work
// so, I'm trying like this

//For the CSS
add_action('wp_head', function() {
echo '<style type="text/css">
.class {
background-color: '. $value2 .';
}
</style>';
});

//For the JS
add_action('wp_footer', function() {
echo '<script type="text/javascript">
var a = '. $value3 .'
</script>';
});

});

现在显然它不起作用,所以我希望你们中的任何人都可以指导我如何以正确的方式完成类似的事情。

如果可以,请帮助而不是对问题投反对票。

最佳答案

应该有更好的方法来做到这一点,但目前只是让它工作,删除 add_action() 部分,只需用您的代码创建一个字符串并返回它:

add_shortcode('example', function( $atts ) {
//extracting the shortcode attributes
extract( shortcode_atts( array(
'value1' => null,
'value2' => null,
'value3' => null
), $atts ) );

//For the CSS
$result = '<style type="text/css">
.class {
background-color: '. $value2 .';
}
</style>';

//For the JS
$result .= '<script type="text/javascript">
var a = '. $value3 .'
</script>';

return $result;
});

关于javascript - 如何在 wordpress 短代码中添加内联 css/js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com