List all Woocommerce products by category

I’m trying to list all of the products and order them by category. Each product has just one category.

I got it to list all the products but on the one page. What I need is to make pagination work. Can anyone help me with this, please?

<?php

$taxonomy     = 'product_cat';
$orderby      = 'menu_order';
$show_count   = 0;      // 1 for yes, 0 for no
$pad_counts   = 0;      // 1 for yes, 0 for no
$hierarchical = 1;      // 1 for yes, 0 for no
$title        = '';
$empty        = 0;
$order        = 'DESC';

$args = array(
     'taxonomy'     => $taxonomy,
     'orderby'      => $orderby,
     'show_count'   => $show_count,
     'pad_counts'   => $pad_counts,
     'hierarchical' => $hierarchical,
     'title_li'     => $title,
     'hide_empty'   => $empty,
     'menu_order' => 'asc',
);

$categories = get_categories($args);

foreach($categories as $category) {

    if ( get_query_var('paged') ) {
        $paged = get_query_var('paged');
    } elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page
        $paged = get_query_var('page');
    } else {
        $paged = 1;
    }

    $args=array(
      'post_type' => 'product',
      //'product_cat' => $category,
      //'showposts' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => array($category->term_id),
            ),
        ),
      'posts_per_page' => -1,
//                            'category__in' => array($category->term_id),
      'paged' => $paged,
      'caller_get_posts'=>1
    );

    //$args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

    $products_query = new WP_Query( $args );
    //$product_array = get_posts($args);

    //$temp_query = $wp_query;
    //$wp_query   = NULL;
    //$wp_query   = $products_query;

    if ( $products_query->have_posts() ) :
        while ( $products_query->have_posts() ) : $products_query->the_post(); ?>
            <?php wc_get_template_part( 'content', 'product' ); ?>

        <?php endwhile;
    endif;
    wp_reset_postdata();

} // foreach($categories

Related posts