Skip to content

Instantly share code, notes, and snippets.

@amirhp-com
Last active August 15, 2022 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amirhp-com/85a652e095c4d160f652bd6164477c59 to your computer and use it in GitHub Desktop.
Save amirhp-com/85a652e095c4d160f652bd6164477c59 to your computer and use it in GitHub Desktop.
WooCommerce move Out-of-stock Products and Products with zero or empty price to end of list
<?php
# @Author: amirhp-com
# @Date: 2022/07/25 05:53:08
# @Email: its@amirhp.com
// order by lowest price to highest
add_filter("woocommerce_default_catalog_orderby", function( $sort_by ){ return 'price';} );
// order zero-price products last, followed by out-of-stock products
add_filter("posts_clauses", "order_by_outofstock_least", 2000);
function order_by_outofstock_least($posts_clauses)
{
global $wpdb;
if (!is_admin() && (is_shop() || is_product_category() || is_product_tag())) {
$posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta instock ON ($wpdb->posts.ID = instock.post_id) ";
$posts_clauses['join'] .= " LEFT JOIN {$wpdb->wc_product_meta_lookup} expro ON $wpdb->posts.ID = expro.product_id ";
$posts_clauses['where'] = " AND instock.meta_key = '_stock_status' AND instock.meta_value <> '' " . $posts_clauses['where'];
$posts_clauses['orderby'] = " instock.meta_value ASC, expro.min_price <> '' OR expro.min_price > 0 DESC, " . $posts_clauses['orderby'];
}
return $posts_clauses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment