function f1_egpaf_meta_or_tax( $where, \WP_Query $q ) { // Get query vars. $tax_args = isset( $q->query_vars['tax_query'] ) ? $q->query_vars['tax_query'] : null; $meta_args = isset( $q->query_vars['meta_query'] ) ? $q->query_vars['meta_query'] : null; $meta_or_tax = isset( $q->query_vars['_meta_or_tax'] ) ? wp_validate_boolean( $q->query_vars['_meta_or_tax'] ) : false; // Construct the "tax OR meta" query. if ( $meta_or_tax && is_array( $tax_args ) && is_array( $meta_args ) ) { global $wpdb; // Primary id column. $field = 'ID'; // Tax query. $sql_tax = get_tax_sql( $tax_args, $wpdb->posts, $field ); // Meta query. $sql_meta = get_meta_sql( $meta_args, 'post', $wpdb->posts, $field ); // Modify the 'where' part. if ( isset( $sql_meta['where'] ) && isset( $sql_tax['where'] ) ) { $where = str_replace( [ $sql_meta['where'], $sql_tax['where'] ], '', $where ); $where .= sprintf( ' AND ( %s OR %s ) ', substr( trim( $sql_meta['where'] ), 4 ), substr( trim( $sql_tax['where'] ), 4 ) ); } } return $where; } add_filter( 'posts_where', 'f1_egpaf_meta_or_tax', PHP_INT_MAX, 2 );
然后在WP_Query查询时,设置’_meta_or_tax’=>true。
例如:
$news_args = [ 'post_type' => ['news', 'class_news'], 'orderby' => 'date', 'posts_per_page' => 3, '_meta_or_tax'=>true, 'tax_query' => array( array( 'taxonomy' => 'class_news_category', 'field' => 'slug', 'terms' => $term_slugs, 'operator' => 'IN', ), ), 'meta_query' => [ [ 'key' => 'classes', 'value' => '"' . get_the_ID() . '"', 'compare' => 'LIKE', ] ] ]; $news_query = new WP_Query($news_args);
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。