Apply jquery script to only woocommerce product pages and categories

I have this script that automatically scrolls down to the primary content on page load.

jQuery(document).ready(function($){
  if ( $(window).width() < 768 || window.Touch) { 
    $('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);} 
});

1. However I would like to only apply it to our woocommerce product pages and categories so it doesnt work on home/blog pages. How would i do that?

I can do this poorly by editing WooCommerce core files but i know that’s a horrible idea so I’m seeking out help on how to do it correctly via my functions.php file.

2. Also i would like to know how to apply it to all pages except the home page should that be a better option later on.

Many thanks!

2 Answers
2

There are two ways you could do that.

1. Using JS only

WordPress themes normally use the body_class() function. As a result you’ll see that the <body> tag will have lots of classes. You can then target pages with a specific class to run your code in JavaScript:

if( $('body.whateverclass').length || $('body.anotherclass').length ){
   // Your JS code here
}

2. Using PHP

You can harness wp_localize_script() to send a flag to your code.

Let’s suppose you enqueued a file called site.js with a handle name of site, in your functions.php you’ll have:

wp_register_script( 'site', 'path/to/site.js' );
wp_enqueue_script( 'site' );

You can now add some flags:

 wp_register_script( 'site', 'path/to/site.js' ); # Unchanged

 $value="";
 if ( is_shop() || is_some_other_condition() ){
    $value="yes";
 }
 wp_localize_script( 'site', 'MYSITE', $value );

 wp_enqueue_script( 'site' ); # Unchanged

You can then check the MYSITE variable in JavaScript:

if( 'yes' === MYSITE ){
  // Your JS code here
}

Edit:
You asked how to put it in the footer.php:

<script>
jQuery(document).ready(function($){
  if( $('body.product-template-default').length || $('body.anotherclass').length ){
    if ( $(window).width() < 768 || window.Touch) { 
         $('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000); 
    }
  }
});
</script> 

Leave a Comment