Woocommerce Custom Product Loop Post Per Page Issue

I have created a custom product loop using “WP_Query” to display Woocommerce product data in Table and its working fine. But 'posts_per_page' => -1, is not showing all the products from sample category.

Currently I have 17 products in Sample category. its only showing 10 products.
I have checked for the problem and found that “WP_Query” is used in posts so
It is taking value of Post per page from
Setiing >Reading >Blog pages show at most

Read More

enter image description here

How I can make ‘posts_per_page’ => -1 to take more that 10 products without changing the WordPress Post per page settings.
The following is my full code.

<?php // The args for the loop
    $args = array(
        'posts_per_page' => -1,
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'sample' // Your category name here
            )
        ),
        'post_type' => 'product',
        'orderby' => 'title',
    ); ?>
    <?php
        $loop = new WP_Query($args); // The Loop
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <table> <!-- Fetching woocommerce data in table -->
        <tr>
          <td><?php the_content(); ?></td> <!-- Content -->
          <td><?php the_title(); ?></td> <!-- Title -->
          <td><?php echo ( $sku = $product->get_sku() ) ? $sku : __( 'N/A', 'woocommerce' ); ?></td> <!-- SKU -->
          <td><?php   echo $product->get_price_html(); ?></td> <!-- Price -->
          <td>
           <?php global $product; // For Adding Add to Cart button in loop
              echo apply_filters( 'woocommerce_loop_add_to_cart_link',
              sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button %s product_type_%s">%s</a>',
              esc_url( $product->add_to_cart_url() ),
              esc_attr( $product->id ),
              esc_attr( $product->get_sku() ),
              $product->is_purchasable() ? 'add_to_cart_button' : '',
              esc_attr( $product->product_type ),
              esc_html( $product->add_to_cart_text() )
              ), $product ); 
            ?>
        </td>
        </tr>
        </table>
        <?php
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>

Related posts

Leave a Reply

3 comments

  1. WooCommerce uses the same “posts per page” setting that is used for blog posts.

    You can modify it in this way

    add_filter( 'loop_shop_per_page', 'so_27395967_products_per_page' );
    function so_27395967_products_per_page(){
        return 12;
    }