Problem using is_single() to enqueue script from functions.php

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…

Read More
<?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' );
 }
}

Related posts

Leave a Reply

1 comment

  1. 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' )