WordPress: Template Specific JavaScript

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:

<?php

get_header(); // http://codex.wordpress.org/Function_Reference/get_header
wp_head(); // http://codex.wordpress.org/Plugin_API/Action_Reference/wp_head
get_footer(); // http://codex.wordpress.org/Function_Reference/get_footer
wp_footer(); // http://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer

?>

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

http://codex.wordpress.org/Pages

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:

<?php

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

get_header(); ?>

<div>
	<h1>My Custom Template</h1>
</div>

<?php

add_action("wp_footer", "addscript_mytemplate");
function addscript_mytemplate() {
	?>
	<script>
		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!");
		});
	</script>
	<?php
}

get_footer(); ?>

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

SIGN UP FOR OUR NEWSLETTER

DON'T WORRY WE HATE SPAM TOO!

RELATED ARTICLES

READY TO BE EXCEPTIONAL? CALL (250) 661-9496 NOW!

Rated Top SEO Agency - Muller Consulting
© AM2 Holdings Corp - 
Muller Consulting 2022