How to enqueue script based on post category?

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,

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

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

Related posts

Leave a Reply

1 comment

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