WooCommerce loop_shop_per_page not working [SOLVED]

According to WooCoomerce documentations, to change the number of WooCommerce products displayed per page, you have to add a filter loop_shop_per_page in your theme’s functions.php.

But you might have face a problem that this does not work. Let us see why.
This is the line of the codes that has loop_shop_per_page filter.

1
$q->set( 'posts_per_page', $q->get( 'posts_per_page' ) ? $q->get( 'posts_per_page' ) : apply_filters( 'loop_shop_per_page', get_option( 'posts_per_page' ) ) );

You’ve probably see now why sometimes the filter does not work. It’s because of the posts_per_page. If posts_per_page is set, the filter does not run.
So for a solution, it’s either to remove the value of posts_per_page or set it as the number you like in loop_shop_per_page.

To set posts_per_page, you can use action woocommerce_product_query like this:

1
2
3
4
5
6
7
add_action( 'woocommerce_product_query', 'woocommerce_product_query' );
 
function woocommerce_product_query( $q ) {
    if ( $q->is_main_query() && ( $q->get( 'wc_query' ) === 'product_query' ) ) {
        $q->set( 'posts_per_page', '5' );
    }
}

With this code, posts_per_page is set to 5. loop_shop_per_page will not run, so you don’t need this.
And this might be also the reason why you can’t use loop_shop_per_page in the beginning, someone before you might have set posts_per_page in the query.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *