Troy Chaplin

Design & Development

Posted in the Blog

Including Scripts on Specific WordPress Templates by Using PHP Conditional Tags

Running scripts in your WordPress theme can give a developer the ability to enhance a websites functionality, but each script being used can add additional load times throughout your sites pages. Using a conditional statement along with WordPress conditional tags to specify when a script will be loaded can help cut down on the unnecessary overhead.

Let’s say you wanted to load a specific script on only your category and post pages, it would be like the following sample. The is_category will add it to any category on your site, while the is_singular will load it on the type specified, in this case, post.


<?php
	if( is_category() || is_singular('post') ) {
		echo '<script type="text/javascript" src="PATH_TO_SCRIPT"></script>';
	}
?>

The is_singular above is different from using the more often seen is_single. By using is_single, the script will be loaded onto all single pages types, this includes any custom post types you may be using.

A good example of this would be using a script called prettyPhoto for displaying portfolio images to creates the gallery style images of work. If the plan is to only use PrettyPhoto for the portfolio you would want to create a conditional statement like this (be sure to change the source path to you script location):


<?php
	if( is_post_type_archive('portfolio') || is_singular('portfolio' ) ) {
		echo '<script type="text/javascript" src="PATH_TO_SCRIPT/jquery.prettyPhoto.js"></script>';
	}
?>

The is_post_type_archive and is_singluar above have portfolio specified, which is the name of the custom post type as it is registered in the functions. PrettyPhoto will now only load when a visitor goes to my portfolio.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>