0

I have a script that I am loading globally to perform a simple action on a specific page. It is showing up an error in the console.log because the other pages dont have the html needed to interact with my script.

To fix this i would like to load the script ONLY on the page type needed. Which is the woocommerce product category pages.

Here is the code I am using in my functions.php file

function read_more_js() {
    echo '<script type="text/javascript" src="/wp-content/themes/marshall-child/js/read-more.js"></script>';
}
// Add hook for front-end <head></head>
add_action('wp_footer', 'read_more_js');

Any help is much appreciated, thanks!

closed as off-topic by Nicolai, Nathan Johnson, cjbj, EAMann Feb 10 '18 at 3:38

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    Woocommerce has the is_product_category() conditional. You should use wp_enqueue_script() though. – Nicolai Feb 6 '18 at 19:08
  • Thanks for the reply! I can use wp_enque method no problem. I am just not sure how to make a conditional statement for the specific type of woocommerce page. IE: The product category page only. – KYSSE Feb 6 '18 at 19:10
  • I wrapped my code above into if (is_product_category()) { MY CODE } but it doesnt wana load at all for some reason when wrapped in that. No erros tho – KYSSE Feb 6 '18 at 19:24
  • 1
    Check the script path. This is neither absolute or relative to a page (except front page). – Max Yudin Feb 6 '18 at 19:38
1

Use wp_unqueue_script for including scripts. Last parametr true include this script in footer. And woocommerce has condotions functions. You need is_product_category() or WordPress default condition is_tax('product_cat'). This code should work for you:

function read_more_js() {
    if ( is_product_category() ) {
        wp_enqueue_script( 'load-more-js', esc_url( get_template_directory_uri() ) . '/js/read-more.js', array( 'jquery' ), null, true );
    }
}
add_action( 'wp_enqueue_script', 'read_more_js' );
  • Try is_tax('taxonomy_name') – Maxim Sarandi Feb 6 '18 at 20:05
  • And? In wp_enqueue_scripts hook this conditions work fine. I doing this more than 4 years. It normal practice. – Maxim Sarandi Feb 6 '18 at 20:11
  • Guys. wp_enqueue_scripts - start after wp hook. See codex hooks – Maxim Sarandi Feb 6 '18 at 20:14

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