So I’m not sure where the issue is yet. But I’m pretty stunned why Bricks header sections disappear once it is active. The snippet sorts sold out products as last items (which should be default anyway thanks to WC it is not). The snippet works like intended but two Bricks section (Top banner - Hero Banner) won’t get rendered and are missing in the html code completely once the user is on the shop or product categories pages. How is that interfering with Bricks template loading is a miracle to me…
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;
Thanks for looking into it. The weird outcome for me was that only section templates with “bricks_after/before_header” attribute where not rendering. No other Bricks query was affected and there are a few other. Like I said I’m not sure if this a expected behavior here.
I found a solution to sort all sold out items last without affecting those Bricks templates with the following code using LEFT JOIN instead:
class iWC_Orderby_Stock_Status {
public function __construct() {
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;
if ((is_shop() || is_product_category() || is_product_tag())) {
$posts_clauses['join'] .= " LEFT JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id AND istockstatus.meta_key = '_stock_status') ";
$posts_clauses['orderby'] = " CASE WHEN istockstatus.meta_value = 'outofstock' THEN 1 ELSE 0 END, " . $posts_clauses['orderby'];
}
return $posts_clauses;
}
}
new iWC_Orderby_Stock_Status;