How to add custom code to WordPress header and footer in functions.php

Categorory:
how to add code to wordpress header and footer

Overview

If you want to install chat widget on your wordpress website or want to add HotJar, Google Analytics, or other third party app script, it can be done easily by adding a code in the functions.php in wordpress instead of installing a wordpress plugin. Adding a wordpress header and footer code insertion plugin may very likely will slow your website.

With the latest WordPress external link updates, header.php and footer.php are not available to edit in Tools -> The File Editor, so the best option is to put the code in functions.php.

Steps

Add code to WordPress header

Use the wp_head hook to add content dynamically to header.php. Add the following code to functions.php in Child theme. If you do not have a Child theme than add it in your main theme functions.php by going to Tools -> The File Editor -> functions.php.

add_action('wp_head', 'your_function_name');
function your_function_name(){
echo '<script> your custom code pasted here </script>';
}

Add code to WordPress footer

Use the wp_head hook to add content dynamically to footer.php. Add the following code to functions.php in Child theme. If you do not have a Child theme than add in your main theme functions.php by going to Tools -> The File Editor -> functions.php.

add_action('wp_footer', 'your_function_name');
function your_function_name(){
echo '<script>  your custom code pasted here </script>';
}

Make sure you change your_function_name at two places in the above codes and add your app script in place of ‘your custom code pasted here’. You can any code in this place.

If you are not using child theme, this code added in functions.php may be overwriiten after a theme update. So, you may need to add this code again after a theme update if you are not using child theme.