最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sort - How to display remaining post ( in post__in ) if posts are less then post per page?

programmeradmin0浏览0评论

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 badge
Add a comment  | 

1 Answer 1

Reset to default 0

I 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.

发布评论

评论列表(0)

  1. 暂无评论