woocommerce offtopic - Show recent products first but "sold out last" in query

I am using WooCommerce and would would like to show the "out of stock" products last in the query on the archi

I am using WooCommerce and would would like to show the "out of stock" products last in the query on the archive page. How can I do that?

Currently we are making the newest product show first with the following custom query:

add_action( 'pre_get_posts', 'mik_exclude_category' );
function mik_exclude_category( $query ) {
    if ( $query->is_main_query() ) {
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
}

So, we would like to do both. Show the newest products first, but show "out of stock" products last no matter how new they are.

Sincerely, Mika

I am using WooCommerce and would would like to show the "out of stock" products last in the query on the archive page. How can I do that?

Currently we are making the newest product show first with the following custom query:

add_action( 'pre_get_posts', 'mik_exclude_category' );
function mik_exclude_category( $query ) {
    if ( $query->is_main_query() ) {
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
}

So, we would like to do both. Show the newest products first, but show "out of stock" products last no matter how new they are.

Sincerely, Mika

Share Improve this question asked Feb 29, 2016 at 22:38 Mika KaltoftMika Kaltoft 131 silver badge3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

If we only have two stock statuses, namely outofstock and instock, we can very easily achieve sorting with pre_get_posts

add_action( 'pre_get_posts', function ( $q ) {
    if (   !is_admin()                 // Target only front end 
         && $q->is_main_query()        // Only target the main query
         && $q->is_post_type_archive() // Change to suite your needs
    ) {
        $q->set( 'meta_key', '_stock_status' );
        $q->set( 'orderby',  'meta_value'    );
        $q->set( 'order',    'ASC'           );
    }
}, PHP_INT_MAX );

You should adjust that to your needs

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745256219a4618972.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信