How to add code to Header or Footer in WordPress

In WordPress we can manually add code to the header or footer of a web site using the following example.

/* Describe what the code snippet does so you can remember later on */
add_action('wp_head', 'your_function_name');
function your_function_name(){
?>
PASTE HEADER CODE HERE
<?php
};

/* Describe what the code snippet does so you can remember later on */
add_action('wp_footer', 'your_function_name');
function your_function_name(){
?>
PASTE FOOTER CODE HERE
<?php
};

An example of adding a Google tag to the head can be something like this:

/* Adding Google tag code to head of the site. google_tag is the name I gave it. */
add_action('wp_head', 'google_tag');
function google_tag(){
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-N82M0N2BYX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-N82M0N2BYX');
</script>
<?php
};

Code can be added to the child theme functions.php file or even better a Code Snippets plugin. Here are two examples Code Snippets plugin or CodeKit.

Example from the Code Snippets plugin.

A Google tag added manually to head in WordPress - Code Snippets plugin
A Google tag added manually to head in WordPress – Code Snippets plugin

Alternate PHP code focused on performance

Comment from Sybre through this issue: Adding Google Analytics to Head – option in SEO Framework located at the SEO Framework Github repo.

add_action( 'wp_head', function() {
    echo <<<'HTML'

<snippet code goes>

HTML;
} );
add_action( 'wp_head', function() {
    echo <<<'HTML'

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-N82M0N2BYX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-N82M0N2BYX');
</script>

HTML;
} );

The following explains the above example snippet as “Nowdoc”.
https://www.php.net/manual/en/language.types.string.php

Sybre mentioned this:
“I used HTML instead of SNIPPET, because some parsers (mainly, VScode) read that and adjust syntax highlighting accordingly. But, you can use any word you’d like.

Note the lack of PHP opening and closing tags. I try to avoid them because even when they’re inside functions that never run, they’ll slow down the entire PHP script.”

Additional resources:

kinsta.com/knowledgebase/add-code-wordpress-header-footer

wordpress.org/plugins/code-snippets

Share the article:

Leave a Reply

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

9 − 7 =