我想在特定的WordPress页面上运行我自己的JavaScript,但只有在第三方的插件运行之后,因为我正在尝试稍微修改该插件。我的问题是,我的JavaScript是在插件脚本之前而不是之后运行的。我在$deps数组中引用插件脚本(即依赖脚本)的方式是否有误?
<?php
// What was originally in the child theme’s function.php file
add_action( \'wp_enqueue_scripts\', \'you_enqueue_styles\' );
function you_enqueue_styles()
{
wp_enqueue_style( \'parent-style\', get_template_directory_uri() . \'/style.css\' );
}
// Added by me to the child theme’s function.php file
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script(\'modify_plugin_js\', \'https://www.example.com/mycustomscript.js\', array(\'greetingnow\', \'jquery\'), \'\',false);
}
}
// Should I even bother putting in a priority of 100 to try and force this to be run last?
add_action(\'wp_enqueue_scripts\', \'load_new_js\', 100);
HTML中的脚本如下所示:
<html>
<body>
<script>
<!-- This is the dependent code that should run first and is put directly into the HTML file by the third party Plugin provider -->
var greetingnow = "Good Morning!";
alert(greetingnow);
</script>
</body>
</html>
最合适的回答,由SO网友:RiddleMeThis 整理而成
试试这个。。。
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script(
\'modify_plugin_js\',
get_stylesheet_directory_uri() . \'/mycustomscript.js\',
array(\'jquery\',\'greetingnow\')
);
}
}
如果不起作用,您使用的插件是什么?
SO网友:Jacob Peattie
使用wp_add_inline_script()
. 它允许您添加和内联依赖于排队脚本的脚本:
function wpse_320377_register_scripts() {
wp_register_script( \'my-script-handle\', \'https://www.example.com/mycustomscript.js\', [ \'jquery\' ], \'\', true );
wp_add_inline_script( \'my-script-handle\', \'var greetingnow = "Good Morning!"; alert(greetingnow);\', \'before\' );
if ( is_page( 692 ) ) {
wp_enqueue_script( \'my-script-handle\' );
}
}
add_action( \'wp_enqueue_scripts\', \'wpse_320377_register_scripts\' );
在该示例中,它注册了一个自定义脚本,
my-script-handle
, 然后使用
wp_add_inline_script()
所以无论何时
my-script-handle
则内联脚本将在其前面输出。结果如下所示:
<script>
var greetingnow = "Good Morning!"; alert(greetingnow);
</script>
<script type="text/javascript" src="https://www.example.com/mycustomscript.js"></script>