0

I am using WooCommerce with Wordpress. I am trying to return all the items within a category, however, I am returning multiple results depending on how many items I have.

When I only had two t-shirt pictures, it would display each picture twice. Once I added a third shirt, it would show each shirt 3 times. My code is:

        $args = array( 
            'post_type' => 'product', 
            'stock' => 1, 
            'posts_per_page' => 9,
            'product_cat' => $pagename, 
        );

        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post();
            foreach ( $loop->posts as $p ) {
                $products = new WC_Product($p->ID);

                echo "<div class='col-md-4'>";
                the_post_thumbnail();
                echo "</div>";

                wp_reset_query();    
            }
        endwhile; 
    ?>

I have tried moving the wp_reset_query() to multiple places (ie within the foreach loop) however the best I get is one div with the proper photo and then a number of blank divs. When using var_dump(), it looks like it may be the new WP_Query($args) itself.

I was previously using wp_reset_postdata() and have switched to wp_reset_query() due to some of the results found on here, but it has not helped.

Thanks in advance.

1

Your loop is wrong, you should not use to foreach inside the while, simply add the classic the_post () using the variable of your loop in this case $ loop

for example

<?php 
    $args = array( 
        'post_type' => 'product', 
        'stock' => 1, 
        'posts_per_page' => 9,
        'product_cat' => $pagename, 
    );

    $loop = new WP_Query( $args );

    while($loop->have_posts()){
        $loop->the_post();
        ?>
        <div class="col-md-4">
            <?php the_post_thumbnail(); ?>
        </div>
        <?php
    }
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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