How to Insert Code Without Plugins

We all know WordPress is awesome, partly because – as we’re so fond of saying around here – “there’s a plugin for everything!”

However, the more plugins you have installed, the more complex the site becomes, and with complexity comes the potential for slow load times. So I always recommend, wherever possible, adding code to your theme rather than installing a new plugin for convenience’s sake.

In this tutorial, we’re going to look at how to add code – such as a javascript file or inline CSS – to all pages, to a single page, to the header and to the footer.

Why You Want to Avoid Editing Your Child Theme’s Files

You should have the correct Parent and Child theme structure for your website, which makes future updates to your theme a lot simpler. However, even with this setup, you can have problems.

For example, let’s say you’ve copied the header.php file from your Parent theme into your Child theme in order to insert tracking code such as Google Analytics or a Facebook pixel.

We know that if you didn’t have a child theme and you modified your theme’s header.php file directly, future updates to the theme may overwrite that file and remove your tracking code.

Copying the header.php file into a Child theme preserves that file so your tracking code is never overwritten. However, what if the Parent theme does update the structure of the header.php file? That means, your Child theme with the old header.php file overrides the newer file in the parent, and at best you miss out on new functionality. At worst, the old file is no longer compatible with the Parent and problems occur.

That’s why, unless you are making significant structural changes to a file, you should avoid using the Child theme for this reason, and make use of your Child theme’s functions.php file.

Let’s look at some real world examples.

Inserting Code into the Header on All Pages

The simplest example would be to add an external javascript file into the header of your website:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

In this instance, WordPress provides an action hook called wp_head which allows us to simply write this code inside the header as the page loads:

function hook_javascript() {
    ?>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <?php
}
add_action('wp_head', 'hook_javascript');

Rather than calling an external file, you can also write javascript directly into the header:

function hook_javascript() {
    ?>
        <script>
            alert('Page is loading...');
        </script>
    <?php
}
add_action('wp_head', 'hook_javascript');

You can essentially add any code to the header of every page using this action hook.

Inserting Code into the Footer on All Pages

Similarly, WordPress provides an action hook called wp_footer which allows us to simply write this code inside the header as the page loads:

function hook_javascript() {
    ?>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <?php
}
add_action('wp_footer', 'hook_javascript');

There are a number of reasons you would add code to the footer instead of the header, but primarily it is done for performance. Unless the code is required to render the above-the-fold content, consider inserting the code in the footer.

One example would be heatmap tracking code, such as Hotjar, which tracks how users interact with your content. This code is not required to render the page, so we put it in the footer.

Also, as I learned recently, when you’re using javascript to modify an element on the page, that element needs to be rendered before it can be modified, so your javascript code needs to run after the element is rendered by the browser.

Inserting Code into the Header on a Single Page

Now let’s modify this functionality so that it only inserts your code on a single page. A real world example of why you might do this is to track conversions – your standard Google Analytics code would be inserted on every page, but then the code to track a conversion would be inserted on the “thank you” page, which you can only get to after a user makes a purchase or fills out a form.

To do this, I like to start by getting the ID of the page in which I want to insert my code. When editing the page, have a look at the URL – you will see the ID there:

https://yousuckatwordpress.com/wp-admin/post.php?post=XXX&action=edit

In this example, the XXX will be the ID. If you are creating a new page, it will need to be published first in order to be assigned the ID. Now, you can add some logic to our function above:

function hook_javascript() {
    if ( is_page( 42 ) ) {
    ?>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <?php
    }
}
add_action('wp_head', 'hook_javascript');

Using the is_page WordPress function, we are checking for page ID 42. The is_page function can also use the slug or title of a page, or even if we’re looking at any single page, like so:

// When any single Page is being displayed.
is_page();
 
// When Page 42 (ID) is being displayed.
is_page( 42 );
 
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
 
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );

I prefer to use the ID because that won’t change, whereas it’s possible a page title or slug may change at some point in the future.

The is_page function can also take an array, which means it can check for more than one page at a time. The contents of the array can be mixed, so it can include IDs, slugs and titles all at the same time:

/** Returns true when the Pages displayed is either post ID 42,
 * or post_name "about-me", or post_title "Contact".
 * Note: the array ability was added in version 2.5.
 */
is_page( array( 42, 'about-me', 'Contact') );

Inserting Code into the WooCommerce Thank You Page

The above code works fine for pages and posts that you can edit through the Dashboard. But what about a virtual page, like the WooCommerce Thank You page. This isn’t a “page” like a Home page or Contact page; this page is dynamically generated by the WooCommerce plugin.

WooCommerce has a large number of it’s own hooks for you to insert code or modify the default code. I won’t go into a lot of detail here, but to give you an example, if we wanted to add Facebook Pixel conversion code to the WooCommerce Thank You page, this is all you would need to do:

/**
 Insert Facebook Pixel conversion into the Thank You page
 */
add_action( 'woocommerce_thankyou', 'insert_fb_conversion' );
function insert_fb_conversion( $order_id ) {
    // Lets grab the order
    $order = wc_get_order( $order_id );
    ?>
        <script>
            fbq('track', 'Purchase', {value: '<?php echo $order->get_order_total(); ?>', currency: 'AUD'});
        </script>
    <?
}

The Plugin Alternatives

As I mentioned, there are plugins that can perform these tasks for you. For example, two of the more popular examples are:

There is nothing inherently wrong with these plugins; in fact, they do a really great job of allowing you to insert your code without needing to write PHP. But as I mentioned at the start of this post, the more plugins you have installed, the more likely your website will start to become sluggish and slow. If all you’re doing is inserting code into a page, the PHP alternative is a much more elegant solution.

Leave a Comment