Last updated on September 13, 2023

Add Code To Footer (wp_footer)

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Add custom code to the footer.

Add code to footer using wp_footer action hook

Adding code to the footer section of a WordPress site can be useful for a variety of purposes, such as adding custom JavaScript files, tracking codes, or other elements. To add code to the footer section of a WordPress site, you can use the wp_footer action hook. Here is an example code snippet:

add_action( 'wp_footer', 'wpsnippets_add_code_to_footer' );

function wpsnippets_add_code_to_footer() {
    // Add custom JavaScript file to the footer section
    wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/custom-script.js', array(), '1.0', true );
    
    // Add tracking code to the footer section
    echo '<script>console.log("Tracking code added to footer");</script>';
}

In this code snippet, we define a function wpsnippets_add_code_to_footer that adds a custom JavaScript file and some tracking code to the footer section of the site using the wp_enqueue_script() function and the echo statement respectively. The array() parameter in wp_enqueue_script() specifies any dependencies for the script (none in this case), while the '1.0' parameter specifies the script’s version. You can load the script in the footer by passing the fifth parameter of wp_enqueue_script() as true. The true parameter specifies that the script should be loaded in the footer section. Lastly, we hook this function to the wp_footer action using the add_action() function.

You can modify this code snippet according to your specific needs, such as adding different JavaScript files or tracking codes. Note that you should always use wp_enqueue_script() function to enqueue JavaScript files instead of directly adding them to the footer section. This ensures that the files are properly loaded and avoids conflicts with other plugins or themes.

Alternative option: Edit the footer.php file directly

Even though this is not always recommended, you can modify the footer.php file of your active theme. The best way to do this, is by using a child theme.

If you don’t know how to make a child theme, you can read about it here in our guide: How to create a WordPress Child Theme (Step by Step)

Here’s an example of how a simple footer.php file might look. You can modify and update this file and add your code before the </body> closing tag, but before the wp_footer() call :

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

?></main>
<footer>Footer content goes here</footer><?php

// Add custom HTML here.

wp_footer();

?></body>
</html>

Please note that any edits to theme files will be overwritten when the theme is updated!

Last updated on September 13, 2023. Originally posted on May 7, 2023.

Leave a Reply

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