skip to Main Content

I Need to Redirect a Custom Page If the Product Count is Zero in a Woocommerce Category Kindly Help me

2

Answers


  1. You just need to add $cat->count to get the count of all products in that category. Hope this helps you out.

    $args = array(
        'number'     => $number,
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
        'include'    => $ids
    );
    
    $product_categories = get_terms( 'product_cat', $args );
    
    foreach( $product_categories as $cat )  { 
       echo $cat->name.' ('.$cat->count.')'; 
    }
    

    Thanks

    Login or Signup to reply.
  2. Assuming that you are accessing the product categories via one of the taxonomy term pages:

    Add this to your functions.php file. Make sure you replace SOME_PATH . '/some-custom-file.php'; with the path to the template you would like to load.

    add_filter( 'template_include', 'redirect_on_empty_product_category' );
    
    function redirect_on_empty_product_category( $template ){
    
      if ( ( $taxonomy_id = get_query_var( 'taxonomy' ) ) && ( $term_id = get_query_var( 'term' ) ) && is_tax( $taxonomy_id, $term_id ) ){
    
        $term = get_term_by( 'slug', $term_id, $taxonomy_id );
    
        if ( $term->count === 0 ){
          $page_url = get_permalink($some_post_id);
          echo sprintf('<script type="text/javascript"> window.location = "%s" </script>', $page_url);
        }
      }
    
      return $template;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search