Home > database >  Query products and order by date and stocks status in WooCommerce
Query products and order by date and stocks status in WooCommerce

Time:12-26

I've set my default orderby query to date.

How do I also include another argument to show in stock products first.

add_filter('woocommerce_get_catalog_ordering_args', 'shop_default_orderby_date');
function shop_default_orderby_date ( $args ) {  
    if( is_shop() && ( ! isset($_GET['orderby']) || 'menu_order' === $_GET['orderby'] ) ) {
    $args['meta_key'] = '';
    $args['orderby'] = 'date';
    $args['order'] = 'desc'; 
    return $args;
    }
}

I came across Multiple orderby arguments on WooCommerce archive page product query.

Is there a way to combine these two?

add_action( 'woocommerce_product_query', 'sort_by_stock_status_and_menu_order', 999 );
function sort_by_stock_status_and_menu_order( $query ) {
    if ( is_admin() ) return;

    $query->set( 'meta_key', '_stock_status' );
    $query->set( 'orderby', 'meta_value menu_order' );
}

CodePudding user response:

Here's the solution to display products by date in descending order (show new products first) and move out-of-stock products to the end of the list:

add_action( 'woocommerce_product_query', 'sort_by_stock_status_and_date', 999 );
function sort_by_stock_status_and_date( $query ) {
    if ( is_admin() ) return;

    $query->set( 'meta_key', '_stock_status' );
    $query->set( 'orderby', array( 'meta_value' => 'ASC', 'date' => 'DESC' )  );
}
  • Related