Skip to content

Instantly share code, notes, and snippets.

@geotsiokos
Created January 10, 2024 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geotsiokos/662cad04a1f4e9e15f2d7d9c15a1b5ce to your computer and use it in GitHub Desktop.
Save geotsiokos/662cad04a1f4e9e15f2d7d9c15a1b5ce to your computer and use it in GitHub Desktop.
Orders products by stock, putting out-of-stock ones to the end of the list
// Orders products by stock, putting out-of-stock ones to the end of the shop and category archives
add_filter( 'posts_clauses', 'order_by_stock_status' );
function order_by_stock_status( $args ) {
global $wpdb;
$join_suffix = $args['join'];
if ( is_woocommerce() && !is_admin() ) {
$args['join'] = " LEFT JOIN {$wpdb->wc_product_meta_lookup} wc_product_meta_lookup ON $wpdb->posts.ID = wc_product_meta_lookup.product_id " . $join_suffix;
$args['orderby'] = ' wc_product_meta_lookup.stock_status ASC, wc_product_meta_lookup.product_id DESC ';
}
return $args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment