Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I add my script files to the very top in the wp_head?

From this guide, using the code below will always add my new script file to the very bottom:

add_action('wp_head','hook_javascript');

function hook_javascript() {

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

    echo $output;
}

Any ideas how I can move my new script files to the top?

like image 340
Run Avatar asked Feb 28 '16 15:02

Run


2 Answers

Use the $priority parameter of the add_action() function.

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

So, choose a very low number and as long as no other plugin/theme uses an even lower number your line will be added at the top.

add_action('wp_head','hook_javascript', -1000);
like image 66
Gerald Schneider Avatar answered Nov 03 '22 00:11

Gerald Schneider


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

By default, this will put it in the header. If you change your mind in the future (and you should), you can pass true as fifth parameter of wp_enqueue_script and it will be placed at the bottom. Refer to the documentation for more info on params.

like image 43
Igor Yavych Avatar answered Nov 03 '22 00:11

Igor Yavych