[英]wp_add_inline_script isn't adding anything to my page, can't figure out why
I want to add inline script to just a single page, so trying to add in the page template file. 我想将内联脚本仅添加到单个页面,因此尝试添加页面模板文件。 However, both placements of the code above or below the footer call results in nothing being outputted in the source.
但是,在页脚调用上方或下方的两个代码放置都不会在源中输出任何内容。
I can't figure out how this is supposed to work, can anyone help? 我不知道这应该如何工作,有人可以帮忙吗?
** Page Template ** **页面模板**
<?php
get_footer('blank');
function cardpay_demo_script() {
wp_add_inline_script(
'jquery',
'$(".btn-next").click(function() {
$(".nav-pills .active").parent().next("li").find("a").removeClass("disabled").trigger("click");
});'
);
}
add_action('wp_enqueue_scripts', 'cardpay_demo_script');
** Footer File ** **页脚文件**
<?php wp_footer(); ?>
</body>
</html>
You are placing the function on the wrong file. 您将函数放置在错误的文件上。 The function should go on the theme's functions.php file and not any default template file or your custom template file .
该功能应位于主题的functions.php文件中,而不应位于任何默认模板文件或自定义模板文件中 。
The reason for this is that in WordPress; 原因是在WordPress中; an Action is a PHP function that is executed at specific points throughout the WordPress Core and since your custom templates will be called way after the hook has been triggered the function will never actually run, so it won't print anything.
一个Action是一个PHP函数,它在整个WordPress Core的特定位置执行,由于自定义模板将在触发挂钩之后被调用,因此该函数将永远不会真正运行,因此不会输出任何内容。
You can use is_page()
or is_page_template()
to determine if it is the page or page template you're looking for. 您可以使用
is_page()
或is_page_template()
来确定它是您要查找的页面还是页面模板。
Here is some additional information on action hooks: https://codex.wordpress.org/Glossary#Action 以下是有关动作挂钩的其他信息: https : //codex.wordpress.org/Glossary#Action
add_action( 'wp_enqueue_scripts', function () {
if( !is_page_template('My Template') ) return;
if ( ! wp_script_is( 'jquery', 'done' ) ) {
wp_enqueue_script( 'jquery' );
}
wp_add_inline_script( 'jquery', '$(".btn-next").click(function() { $(".nav-pills .active").parent().next("li").find("a").removeClass("disabled").trigger("click");
});' );
});
or you can just print your scripts on the footer using the wp_footer hook. 或者您也可以使用wp_footer钩子在脚注上打印脚本。 Just put this on your theme's functions.php file
只需将其放在主题的functions.php文件中
add_action('wp_footer', function (){
if( !is_page_template('My Template') ) return;
?>
<script type="text/javascript">
jQuery(".btn-next").click(function() { jQuery(".nav-pills .active").parent().next("li").find("a").removeClass("disabled").trigger("click");
});
</script>
<?php
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.