Custom WooCommerce Query String to Display Only First 3 Products

33 Views Asked by At

I have tried the following URL parameters below, and orderby parameter works fine, displaying all the products sorted by date, but I want only to display the 3 first products (limit parameters doesn't work):

../shop/?orderby=date&limit=3

Anyone had success?

1

There are 1 best solutions below

0
LoicTheAztec On BEST ANSWER

This can be done via a function hooked in woocommerce_product_query action hook.

  1. Using posts_per_page argument:

When setting 3 to posts_per_page argument, it displays 3 products per page (so not convenient).
And if we set additionally nopaging argument to false, all products are displayed without pagination.

  1. Using post__in argument (the right way):

This requires to pre-query product IDs sorted by date, with your defined "limit" URL parameter. The first 3 products are displayed without pagination.

The code:

add_action( 'woocommerce_product_query', 'enable_query_var_limit', 10, 2 );
function enable_query_var_limit( $query, $q ) {
    error_log(print_r($query, true));
    if ( ! is_admin() && isset($_GET['limit']) && isset($_GET['orderby']) 
    && is_numeric($_GET['limit']) && $_GET['orderby'] === 'date' ) {
        $query->set( 'post__in', wc_get_products( [
            'status'    => 'publish',
            'limit'     => intval($_GET['limit']), 
            'orderby'   => 'date',
            'return'    => 'ids',
        ] ) );
    }
}

Code goes in functions.php file of your child theme (or in a plugin).

Tested and works with ?orderby=date&limit=3 query string (URL variables).