将Wordpress插件脚本排在所有其他JS下面

时间:2013-11-11 19:10:03

标签: javascript php jquery wordpress wordpress-plugin

我正在开发一个简单的Wordpress应用程序,但我遇到了一个问题,因为所有插件脚本都是在我functions.php排队的那些之前呈现的。

以下是functions.php的示例部分:

function my_scripts() {
    wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
    wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts');

需要注意的重要一点是(按照最佳实践,我的JS设置为在页面底部呈现。

我还在主题上运行了几个插件。问题是输出看起来像这样:

<!-- Note the plugin appears first -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/my-plugin/acl-plugin.js'></script>
<!-- And the main JS appears second -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/my-theme/javascripts/app.js'></script>
</body>
</html>

如何强制Wordpress显示主JS(我相信wp_head()呈现的主JS出现在页面的最底部?

1 个答案:

答案 0 :(得分:17)

WordPress wp_head()方法只输出将WordPress wp_enqueue_script()中的最后一个参数设置为 false 的脚本或样式..当它设置为 true 时,它将通过 wp_footer()

在页脚中呈现

您可以通过调整 add_action()

中的 $ priority 参数来更改其调用和插入时的优先级

<强> http://codex.wordpress.org/Function_Reference/add_action

  

$优先       (int)(可选)用于指定与特定操作关联的函数的执行顺序。较低的数字与先前的执行相对应,具有相同优先级的函数按照它们添加到操作的顺序执行。默认值:10

add_action( $hook, $function_to_add, $priority, $accepted_args );

还要看下面两个WordPress方法:

wp_enqueue_script()

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

wp_register_script()

https://developer.wordpress.org/reference/functions/wp_register_script/

wp_register_script( string $handle, string $src, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

试试这个..

您可能必须使用 $ priority 参数

function my_scripts() {
        wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
        wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts', 20, 1);