Created
August 1, 2017 08:03
-
-
Save shreyans94/065bfdf21ebff9556356d0d944a80318 to your computer and use it in GitHub Desktop.
Sort out of stock in category & Shop pages for Woocommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add custom Theme Functions here | |
/** | |
* Sorting out of stock WooCommerce products - Order product collections by stock status, in-stock products first. | |
*/ | |
class iWC_Orderby_Stock_Status | |
{ | |
public function __construct() | |
{ | |
// Check if WooCommerce is active | |
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) { | |
add_filter('posts_clauses', array($this, 'order_by_stock_status'), 2000); | |
} | |
} | |
public function order_by_stock_status($posts_clauses) | |
{ | |
global $wpdb; | |
// only change query on WooCommerce loops | |
if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) { | |
$posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) "; | |
$posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby']; | |
$posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where']; | |
} | |
return $posts_clauses; | |
} | |
} | |
new iWC_Orderby_Stock_Status; | |
/** | |
* END - Order product collections by stock status, instock products first. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment