WP Woocommerce is_product_category not working

I am selling a single product on my woocommerce store, and beside that product I sell few accessories for him, so I want to use two templates. Next to content-single-product.php file I created another one called content-single-accessory.php and edit that template file.

Next I created two categories: product and accessory, product itself is added inside product category and accessories are added inside accessory category. Now it comes the problem I am facing with. Inside single-product.php I did this:

Read More
    <?php if (is_product_category( 'product' )) { ?>

    <?php wc_get_template_part( 'content', 'single-product' ); ?>

    <?php } else  { ?>

    <?php wc_get_template_part( 'content', 'single-accessory' ); ?>

    <?php } ?>

and when I visit the page with product category it does not show the product template but it shows content-single-accessory.php. Or to be more clear, above if statement does not work at all and second template is always showed. What I am doing wrong here?

Thanks!

Related posts

Leave a Reply

2 comments

  1. This is good habit to try with is_product_category() or is_category() in wordpress but when the situation is not going in your way then don’t make it complicate.

    1. Get your current page url

      $current_url = (isset($_SERVER['HTTPS'])
                      ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
      
    2. And check for category page simple,

      if(strpos($current_url,'product-category') !=false
                                || strpos($current_url,'brand') !=false ) {
      
      }
      
  2. pleace try this and let me know:

    <? 
    $terms = get_the_terms( $post->ID, 'product_cat' );
    
    foreach ($terms as $term) {
       if($term->slug == 'product') : ?>
    
          <?php while ( have_posts() ) : the_post(); ?>
             <?php wc_get_template_part( 'content', 'single-product' ); ?>
          <?php endwhile; // end of the loop. ?>
            <?php else :?>
                <?php wc_get_template_part( 'content', 'single-accessory' ); ?>
            <?php endif; 
    }?>
    

    EDIT:
    add <? to the beginning