发生此错误可能是因为在重写post子句时未检查post类型。
筛选器回调需要第二个参数,即WP_Query
实例,然后使用它检查post_type
是你需要的。如果不进行检查,您将覆盖网站在这些WooCommerce页面上发布的任何类型的帖子的每个数据库查询。
请尝试使用此已编辑的代码,并在其中检查我的注释:
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;