Looking to add code before the closing head tag in a WordPress site?
Most well-coded themes will have a call to wp_head()
function before </head>
in header.php
which is used by all pages of your WordPress website.
That function has a single line:
do_action( 'wp_head' )
which runs all the callback functions that have been added to that action hook.
Therefore, we can place our desired code in a callback function that will run when WordPress processes the wp_head()
function.
Add this in your child theme’s functions.php
:
add_action( 'wp_head', function () {
echo 'test';
} );
Reload any page of your site, view its source and you should now see the string test
before the closing head tag.
Depending on the order in which your theme or a plugin or other custom code adds its own callback functions that hook into the wp_head
action your custom code – echo 'test'
in this example might not be added exactly right before </head>
.
So if you want to add some custom HTML right before </head>
, specify a lower priority as the third argument to add_action()
function. Like this:
add_action( 'wp_head', function () {
echo 'test';
}, 100000 );
The default priority value is 10.
By specifying a low priority value of 100000 (the higher the number, the lower the priority), we are telling WordPress to call our callback (the anonymous function) later in the execution queue and so it will get printed later after all other callback functions that are attached to the wp_head
hook have run.
Here’s a practical example:
add_action( 'wp_head', function () { ?>
<script src="https://t7a7b97da.emailsys1a.net/form/###/###/7e7c939b5c/popup.js?_g=##########" async></script>
<?php }, 100000 );
References
http://developer.wordpress.org/reference/functions/wp_head/
http://developer.wordpress.org/reference/hooks/wp_head/
https://developer.wordpress.org/reference/functions/add_action/