Load scripts only on custom post type and specific taxonomy pages

Now here we will be discussing how to call these specific scripts only on the custom post type and taxonomy pages. So for our discussion we will take that we have created a custom post type called “books” with a taxonomy “author” and the all book-list page called “allbooks”. So lets learn how to load the css files and javascripts only on specified pages in wordpress 3(+) i.e custom post types and wordpress taxonomy pages.

Although these are all simple code snippets but are not available at the right moment!

1. If the page listing all the custom post type “books” is named “allbooks”.

This is nothing special just remembering once again how to load scripts on wordpress pages with the page name.

<?php
if (is_page('allbooks'))
{?>
<link type="text/css" rel="stylesheet" href="<?php bloginfo('template_url'); ?>/books.css" />
<?php } ?>

2. If the custom post type name is “books” listing all the custom “books” posts.

This is similar to the word-press single post pages, i.e only for the  single pages for “books” custom post type.

<?php if(is_singular('books') ) { ?>
<link type="text/css" rel="stylesheet" href="<?php bloginfo('template_url'); ?>/books.css" />
<?php } ?>

3. If the taxonomy name is “author” listing all the author posts.

(A) This is similar to the word-press category archives, so here comes our custom post type archive for “author” taxonomy.

<?php if (is_tax('author')) { ?>
<link type="text/css" rel="stylesheet" href="<?php bloginfo('template_url'); ?>/books.css" />
<?php } ?>

(B) This code "if (is_tax('author'))" can also be used in the functions.php to add a taxonomy specific  script or style.

function init_customizations() {
 if (is_tax('author')) {
 wp_register_script('author_script',get_bloginfo('template_directory').'/js/author_script.js', array(), '1.0.0' );
 wp_enqueue_script('author_script');
 wp_register_style('author_style',get_bloginfo('template_directory').'/css/author_style.css', array(), '1.0.0', 'screen');
 wp_enqueue_style('author_style');
 }
}
add_action( 'wp_enqueue_scripts', 'init_customizations', 0 );

CONCLUSION

Each mention of css style sheets and scripts in an html/php document increase the http request by one there by increasing load time. So whenever possible combine all css into one style sheet and all scripts into a single script or load and call for the script files only when necessary just as I showed the above examples for the wordpress custom post types and taxonomy pages.

Share this post:

Priyanka Naskar Majumder - the Owner, Eyedea LAB. Graphic & Web Design Studio, lives in Kolkata, India. Interested in: Usability research, Graphic Design, Web Design & Development.


2 Comments

One Trackback


Leave a Reply

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

*

Allowed HTML tags: <strong> <em> <pre> <code> <a href="" title="">