Adding code to WordPress header or footer is needed when you have Google Analytics, Facebook Pixel, Hotjar or any other service code that has to be placed in that specific place in order to run normally. Of course you are not limited to some 3rd party services – you can put your own code to WordPress header and footer.

You can add code snippets directly to your header.php and footer.php files, but there is a better way – to use your functions.php file and the appropriate WordPress hook. This lets you keep all your snippets in one place and avoid modifying core theme files.

PHP Snippet: Add code to the WordPress Header

You need to use the wp_head hook to add content to the <head></head> dynamically. Just add the following piece of code to your child theme’s functions.php.

add_action('wp_head', 'change_this_name_of_your_function');
function change_this_name_of_your_function(){
echo '<script> YOUR CODE HERE </script>';
}

PHP snippet: Add code to the WordPress Footer

You need to use the wp_footer hook to add content to the <footer></footer> dynamically. Just add the following piece of code to your child theme’s functions.php.

add_action('wp_footer', 'change_this_name_of_your_function');
function change_this_name_of_your_function(){
echo '<script> YOUR CODE HERE </script>';
}

Make sure to change the name of the function on both places: “change_this_name_of_your_function”. Note that you can add anything to the header and footer, not just a <script> like in the example above.

Using those WordPress Hooks, you don’t need to copy your entire header.php file to your child theme’s folder. If you don’t use a child theme, any code that you add to your header or footer will get overwritten if you update your WordPress theme.

You can add your tracking scripts to the Footer or Header for example to a specific group of users like user who are logged-in, or users who have a specific WordPress capability.

Learn more about wp_head hook

Learn more about wp_footer hook




Recent Articles

Blog Categories

Comments

Leave a comment

Leave a Reply

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.