WordPress wp_head - 如何将新的脚本文件添加到顶部?

WordPress wp_head - how to add new script files to the top?

如何将我的脚本文件添加到 wp_head 中的最顶部?

从本指南开始,使用下面的代码将始终将我的新脚本文件添加到最底部:

add_action('wp_head','hook_javascript');

function hook_javascript() {

    $output="<script> alert('Page is loading...'); </script>";

    echo $output;
}

关于如何将我的新脚本文件移动到顶部的任何想法?

function enqueue_assets()
{
    wp_enqueue_script('your_plugin_js', plugins_url('/my.js', __FILE__));
}
add_action('wp_enqueue_scripts', 'enqueue_assets');

默认情况下,这会将其放在页眉中。如果你以后改变主意(你应该改变主意),你可以将 true 作为 wp_enqueue_script 的第五个参数传递,它将放在底部。有关参数的更多信息,请参阅 documentation

使用add_action()函数的$priority参数。

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

$priority
(int) (Optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
Default value: 10

因此,选择一个非常低的数字,只要没有其他 plugin/theme 使用更低的数字,您的行就会被添加到顶部。

add_action('wp_head','hook_javascript', -1000);