Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have scripts for various little tools I have made using some js and html. I want the js to load only on specific single posts in side a specific category. I have tried the following code and it does not work. I removed the "if" statement and the script does run and work so it's a matter of fixing the if statement.

Here's what I've got so far,

    if ( is_single() && in_category( 'mouse' ) ) {
wp_enqueue_script( 'mousescript');
}

Thank you very much for any and all help, it's greatly appreciated!

share|improve this question
    
Where did you put that code? –  s_ha_dum Jan 30 '13 at 22:01

1 Answer 1

up vote 0 down vote accepted

Inside your theme's functions.php add something like this:

function my_conditional_enqueue_script() {
    global $post;
    if (is_single($post->ID) && in_category('mouse', $post->ID)) {
        wp_enqueue_script('mousescript');
    }
}
add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script');

Also, make sure you use wp_register_script before you attempt to enqueue.

share|improve this answer
    
Hey @The Maniac, thanks for getting back to me! I tried that bit of code and no luck... I am inside my child themes function.php and yeah I have already registered the script - 'wp_register_script('mousescript', get_stylesheet_directory_uri() . '/js/myscript.js');' if I just use 'wp_enqueue_script('mousescript');' after it it works. It only stops working after using an if statement. –  Gk3Biz Jan 30 '13 at 21:50
    
Hmm, I'm doing this in a theme I'm currently developing and it worked for me. Seems obvious, but are you sure you have posts in the 'mouse' category? Are you sure the slug of that category is exactly mouse? Are you browsing to a single post (or page)? –  The Maniac Jan 30 '13 at 21:57
    
excuse me you're absolutely correct. The slug was slightly incorrect and after fixing it, the script works perfectly. Thank you again, it works beautifully! –  Gk3Biz Jan 30 '13 at 22:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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