skip to Main Content

I’m trying to get the posts count inside my product category page loop (Woocommerce), but it just doesn’t work. Does anyone knows why?

Woocommerce uses the same file archive-product.php for displaying both Shop Page and Product Category Page. In my archive-product.php, I passed the value to a variable using a Woocommerce function before the loop starts:

do_action( 'woocommerce_before_shop_loop' );

$totalproducts = wc_get_loop_prop( 'total' );

woocommerce_product_loop_start();

if ( wc_get_loop_prop( 'total' ) ) {
    while ( have_posts() ) {
        the_post();
        wc_get_template_part( 'content', 'product') );
    }
}

woocommerce_product_loop_end();

Inside the content-product.php, I call the variable and then I use it to add an inline z-index to each post, decreasing it at each post.

<?php global $totalproducts; ?>

<div class="product-item" style="z-index: <?php echo $totalproducts; ?>;">
   content of the post
</div>

<?php $totalproducts = $totalproducts - 1; ?>

For the Shop Page it works perfectly, but for the Product Categories pages it just doesn’t work, the variable comes empty. If I echo the variable before the loop starts in my archive-product.php it shows the post count from the category, so it’s working fine for both pages. But I just can’t get the variable inside the loop, specifically in the Categories Pages. Does anyone knows why this is happening?

Am I doing something wrong?

2

Answers


  1. Chosen as BEST ANSWER

    Well, I finally found a solution for my problem.

    What I did was adapting my code and create the woocommerce.php in my theme's directory instead of overriding the archive-product.php.

    And then the file finally got the variable for the product category pages too. I have no idea of why this happened.


  2. Maybe using the global variable $wp_query and its property post_count, replacing in your code:

    $totalproducts = wc_get_loop_prop( 'total' );
    

    by this:

    global $wp_query;
    
    $totalproducts = wc_get_loop_prop( 'total' ) ? wc_get_loop_prop( 'total' ) : $wp_query->post_count;
    

    It could better work.


    Also you can simplify this line:

    <?php $totalproducts = $totalproducts - 1; ?>
    

    by:

    <?php $totalproducts--; ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search