0

I use a plugin "Post Tags and Categories for Pages" which adds categories to pages.

My intention is to enqueue an external script on a page, only when it's needed. So if I assign a page to a category, only that page gets the script loaded.

I have this hook:

to function my_conditional_enqueue_script1() {
    global $page;
    if ( is_single() && in_category( '19' ) ) { 
    wp_enqueue_script( '/members/application/cart/views/public/js/cart.js' );
    }
}
add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script1');

Seems like it should work, but it doesn't. Any suggestions?

Or, is it more advisable to maybe add the script on a page my using short-codes (wrap the hook in plugin somehow)?

Thanks for any help with this.

1

is_single() doesn't work for the page post type, use is_page() instead.

You're also missing the first argument for wp_enqueue_script, the script handle. Source should be the second argument.

function my_conditional_enqueue_script1() {
    if ( is_page() && in_category( 19 ) ) { 
        wp_enqueue_script(
            'my-cart-script',
            '/members/application/cart/views/public/js/cart.js'
        );
    }
}
add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script1');
  • Tested and it's works perfectly. I'm still leaning. Thank you very much. – andrew5555 Jan 19 '18 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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