The error occurs probably because you don’t check for the post type when overriding the post clauses.
Your filter callback needs a second parameter which is a WP_Query
instance, and then use it to check if the post_type
is what you need. If you don’t check for that, you’ll be overriding every single database query for any type of posts your website does on those WooCommerce pages.
Please try using this edited code, and check my comments in it:
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' ) ) ) ) {
// Added the fourth parameter 2 for the number of parameters to pass to the callback method
add_filter( 'posts_clauses', [ $this, 'order_by_stock_status' ], 2000, 2 );
}
}
/**
* @param string[] $posts_clauses
* @param \WP_Query $query
*
* @return string[]
*/
public function order_by_stock_status( $posts_clauses, $query )
{
// Bail early if the post_type is not what we need
if ( $query->get( 'post_type' ) !== 'product' ) {
return $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;