I am sorting product on product category page. I want to display sale product at first and show remaining product after it. I am using pre_get_posts hook to modify query.
My CODE
function modify_query( $query ) {
if( ! is_admin() && $query->is_main_query() && is_product_category() ){
$product_ids_on_sale = wc_get_product_ids_on_sale();
$query->set( 'post__in', $product_ids_on_sale );
$query->set('orderby', 'post__in' );
}
}
add_action( 'pre_get_posts', 'modify_query' );
But this query is only showing sale products. I want to show ramaning post after the sale products. For example if my post_per_page is 10, and sale product is 2. Then I want to display 2 sale and 8 remaining products.
I am sorting product on product category page. I want to display sale product at first and show remaining product after it. I am using pre_get_posts hook to modify query.
My CODE
function modify_query( $query ) {
if( ! is_admin() && $query->is_main_query() && is_product_category() ){
$product_ids_on_sale = wc_get_product_ids_on_sale();
$query->set( 'post__in', $product_ids_on_sale );
$query->set('orderby', 'post__in' );
}
}
add_action( 'pre_get_posts', 'modify_query' );
But this query is only showing sale products. I want to show ramaning post after the sale products. For example if my post_per_page is 10, and sale product is 2. Then I want to display 2 sale and 8 remaining products.
Share Improve this question asked Jan 6, 2021 at 4:38 PrajwolPrajwol 11 bronze badge1 Answer
Reset to default 0I think the simplest, but not necessarily the most performant, would be using two WP_Query loops, one using $query->set( 'post__in', $product_ids_on_sale );
and other using $query->set( 'post__not__in', $product_ids_on_sale );
because these are mutually exclusive. One loop would be used for the main query and other for second loop as show in this example in the documentation.
You would need to account for the number of items in each loop based on the number of items in the $product_ids_on_sale
variable AND pagination. And I would the main query for the products NOT in sale.