Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the polylang domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/vajnabot/public_html/wp-includes/functions.php on line 6121
Vajna Botond | Online portofolio | How to get WooCommerce products grouped by their categories?

Vajna Botond

Designer

How to get WooCommerce products grouped by their categories?

<?php

// === GET PRODUCTS BY CATEGORY 
    $args = array(
        // 'number'     => $number,
        'orderby'   => 'title',
        'order'     => 'ASC',
        'hide_empty' => true,
        // 'include'   => $ids
    );

    $product_categories = get_terms( 'product_cat', $args );

    $count = count($product_categories);

    if ( $count > 0 ){
        foreach ( $product_categories as $product_category ) {
            echo '<h4><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</a></h4>';   
            
            $args = array(
                'posts_per_page' => -1,
                'tax_query' => array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'product_cat',
                        'field' => 'slug',
                        // 'terms' => 'white-wines'
                        'terms' => $product_category->slug
                    )

                ),
                'post_type' => 'product',
                'orderby' => 'title,'
            );

            $products = new WP_Query( $args );

            echo "<ul>";

                while ( $products->have_posts() ) {
                    $products->the_post();
                    ?>
                    <li>
                        <a href="<?php the_permalink(); ?>">
                            <?php the_title(); ?>
                        </a>
                    </li>

                    <?php
                }
            echo "</ul>";
            }
    }

?>