How to add a script on top of head in WordPress

Here’s an example of a WordPress function that you can place in your functions.php file to add a script to the top of the <head> section:

function add_script_to_wp_head() {
    ?>
    <script>
        // Your script code goes here
        console.log('This script is added to the top of the <head> section.');
    </script>
    <?php
}
add_action('wp_head', 'add_script_to_wp_head', 0);

In the above code, we define a function called add_script_to_wp_head that contains the script you want to add. The console.log statement is just an example; you can replace it with your own script code.

We then use the add_action function to hook the add_script_to_wp_head function to the wp_head action. The third parameter, 0, specifies the priority of the action. By setting it to 0, we ensure that our script is added to the very top of the <head> section.

Save the functions.php file, and your script will be added to the top of the WordPress <head> section on all pages.

What if there are more scripts with priority 0?

If you want to place your script on top of another script or code that already has a priority of 0, you can use a negative priority value to ensure that your code executes before the existing one. Here’s an updated version of the function that allows you to specify a negative priority:

function add_script_to_wp_head() {
    ?>
    <script>
        // Your script code goes here
        console.log('This script is added to the top of the <head> section.');
    </script>
    <?php
}
add_action('wp_head', 'add_script_to_wp_head', -1);

In the above code, we set the priority of the wp_head action to -1, which is a negative priority value. This means that your script will be added to the <head> section before any other scripts or code that has a priority of 0.

By using a negative priority, your script will be added to the very beginning of the <head> section, regardless of any existing code that has a priority of 0. Adjust the priority value as needed to achieve the desired placement relative to other code.

For more WordPress Tips & Tricks, feel free to click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like