'How to add a script at the beginning of the <head> tag before all other scripts in WordPress
I've been looking for a few days in the stack overflow here but I can't find the answer to my problem. I'm trying to add the Cookie Yes script, to insert the cookie banner on my WordPress site. The script must be loaded at the beginning of the tag before any other script, because it must preventively block the other Facebook, analytics, etc. scripts. I tried adding this to my child-theme's function.php file:
add_action( 'wp_head', 'cookieyes_script', 0 );
function cookieyes_script() {
echo '<!-- Start cookieyes banner --><script id="cookieyes" type="text/javascript" src="https://cdn-cookieyes.com/client_data/557849044ec07b9e401db693/script.js"></script><!-- End cookieyes banner --> ';
}
But the plugins that add the other scripts are always inserted before the one I want to add. Thank you very much.
Here the real example:
in function.php file
/* add script at the top of head tag */
add_action('wp_head', 'add_top_head_script',0);
function cookieyes_script() {
echo '<!-- Start cookieyes banner --> <script id="cookieyes" type="text/javascript" src="https://cdn-cookieyes.com/client_data/754d136f697eda5270dfe657/script.js"></script> <!-- End cookieyes banner -->';
}
Solution 1:[1]
One way you might be able to get this done is with the wp_head
action with 0
as the priority...
function cookieyes_script() {
echo '<!-- Start cookieyes banner --><script id="cookieyes" type="text/javascript" src="https://cdn-cookieyes.com/client_data/557849044ec07b9e401db693/script.js"></script><!-- End cookieyes banner --> ';
}
add_action("wp_head", "cookieyes_script", 0);
One issue here is that if another script uses this same priority of 0
the hook that is registered first will be higher. That said the default priority for add_action
is 10
so probably safe here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mikerojas |