There are a ton of ways to include specific scripts within a particular page or custom template by utilizing the WordPress API. However, in this simple article I want to demonstrate my favorite method of dealing with a script block that is hopelessly tied to a particular template.

First, I’m assuming you understand the following methods:


get_header(); //
wp_head(); //
get_footer(); //
wp_footer(); //


I’m also assuming that you’ve created your own Page Template before:

As developers, we all have our own preferences and styles, and when it comes to separation of concerns (a much deeper issue), many developers feel a constant urge to keep all files of a particular type (styles, javascripts) within an area designated to that type. While I completely subscribe to this sort of organization, I also love having related scripts right at my fingertips.

Here’s An Example

I want to include my simple script within the footer, and particularly when the wp_footer method is called. I could create a script file dedicated to My Custom Template, place it within my `javascripts` folder within my theme directory, use the wp_enqueue_script method within my functions.php file, and finally use a conditional to include my script only when My Custom Template is being used … yeah … I say no.

A Better Way

The above process is too convoluted. Instead, we’ll do it another way:


/* Template Name: My Custom Template
------------------------------------------------------------ */

get_header(); ?>

	<h1>My Custom Template</h1>


add_action("wp_footer", "addscript_mytemplate");
function addscript_mytemplate() {
		jQuery(document).ready(function($) {
			// now that the document has loaded, do something within your script
			alert("Yay! I'm only included within this specific tempalte!");

get_footer(); ?>

So simple. It’s organized, convenient, and has a very clear purpose.

© Muller Consulting 2021