Including a Javascript File in a Specific WordPress Page

Including a particular Javascript file for a specific page or post in WordPress is something that can be useful so that you do not needlessly load the file for every page of the site. Let’s take the example where we want to include the file “page-specific.js” file in the WordPress page “A Specific Page”. In this case I’m assuming the path to your page-specific.js file is:

/wp-content/themes/your-child-theme/js/page-specific.js

In the functions.php file of the child theme enter this code:

add_action( 'wp_head', 'custom_include_script' );

function custom_include_script()
{
    if(is_page( 'a-specific-page' ))
    {    
    ?>
	<script src="<?php echo esc_url( get_stylesheet_directory_uri() . '/js/page-specific.js"' ); ?>" type="text/javascript"></script>
    <?php  
    }
}

The PHP Is pretty simple to understand. We’ve added an action to the wp_head call. The action checks if the page is the page we are interested in, and if it is, it echoes out the HTML required to include the JS file. The get_stylesheet_directory_uri() call gets the directory of the child theme we’re using.

This entry was posted in WordPress on by .

About markn

Mark is the owner and founder of Timesheets MTS Software, an mISV that develops and markets employee timesheet and time clock software. He's also a mechanical engineer, father of four, and a lifelong lover of gadgets.