WooCommerce – Loop through sale products by category but restrict to one category per product

Question

I have this loop working at the moment, although products are listed in multiple categories and are looping through multiple times. How do I restrict output to one category per sale product?

$count = count($product_categories);
if ( $count > 0 ){
    foreach ( $product_categories as $product_category ) {

        $args = array(
            'posts_per_page' => -1,
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => $product_category->slug
                )
            ),
            'post_type' => 'product',
            'meta_query' => WC()->query->get_meta_query(),
            'post__in' => array_merge( array( 0 ), wc_get_product_ids_on_sale() ),
            'order' => 'DESC',
        );

        $products = new WP_Query( $args );

        if($products->have_posts()){
            echo '<div class="row product-list-row">';
            echo '<h2><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</a></h2>';

            echo '<ul class="product-category-list">';
            while ( $products->have_posts() ) {
            global $product;
                $products->the_post();

                ?>
                    <li>
                        <a class="special-product" href="<?php the_permalink(); ?>">
                            <h4><?php the_title(); ?></h4>

                        </a>
                    </li>
                <?php
            }
            echo "</ul>";
            echo '</div>';
        }

    }
}

Thanks for any help provided.

0
, , DIM3NSION 2 years 2019-11-23T11:28:27-05:00 0 Answers 96 views 0

Leave an answer

Browse
Browse