3

I'm having trouble only adding scripts to single post pages. I need to both include and exclude certain scripts using is_single() but it doesn't work either way I try it.

I have the template tag on the top of custom single post templates...

<?php /* Template Name: Single Default */ ?>

And I use this to call a script from the functions.php

if (!is_admin()) {
 if (is_single()) {
    wp_register_script( 'jquery-scroll', get_bloginfo('stylesheet_directory').'/libs/jquery.jscrollpane.min.js' );
wp_enqueue_script( 'jquery-scroll' );
 }
}

1 Answer 1

9

This could be one of a few different issues.

1. Wrong Hook / Not Hooked

You need to make sure that wp_enqueue_script is hooked to wp_enqueue_scripts. Otherwise, the call can get fired too late or (possibly in this case?) too early?

Try this (also with your php cleaned up a bit:

function wpse53364() {
    if( !is_admin() && is_single() ) {
        wp_register_script( 'jquery-scroll', get_bloginfo('stylesheet_directory').'/libs/jquery.jscrollpane.min.js' );
        wp_enqueue_script( 'jquery-scroll' );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse53364' );

2. Incorrect Template Use

It's unclear from your question, but if you're using single.php for your "custom single posts template," you shouldn't be using that "Template Name:..." header. The WordPress template hierarchy will automatically know which file to use.

3. Wrong Conditional Tag

The fact that you're using a custom page template makes me wonder whether you're trying to use this script to enqueue the script on PAGES as opposed to POSTS. If that's the case, you need to replace is_single() with is_page() or is_singular( 'page' )

4
  • I use a function that lets me put different single post templates into a folder in my child theme and then I call them conditionally from the single.php. Is that the problem? Commented May 26, 2012 at 1:19
  • Regarding the template, I don't think there's anything inherently wrong with that. Since page's are the only post type that supports page templates there's probably not much you can do if you need to recreate something similar.
    – mrwweb
    Commented May 26, 2012 at 16:59
  • The real root of the problem was not using an API hook to check the is_single() status. I think even the init hook is too soon for this (and the theme functions.php is loaded right before init fires), so I usually use the template_redirect hook for anything that depends on the is_*() conditionals. Commented May 27, 2012 at 16:41
  • 2
    is_singular('custom_type'); worked for me Commented Oct 14, 2018 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.