WordPress 自定义 WP_Query 循环如何支持 tax_query or meta_query 参数

WordPress 的循环函数都是 and 方式链接,对于单个的 meta_query 或者 tax_query 字段内部才能使用 or,那么如果我们想要实现 tax_query or meta_query 的关系,WordPress 默认是不提供支持的。泪雪网 https://www.leixue.com

WordPress WP_Query 自定义

子凡最近为了满足泪雪网的功能需求,查找了大量的教程,甚至想过用两个 WP_Query 循环来实现这样的功能,后来通过 Google 搜索到一个相关的答案,为此子凡整理并分享出来,这样当你在使用 WordPress 的 WP_Query 来自定义循环,并且完美的支持 tax_query or meta_query。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Modify WP_Query to support 'meta_or_tax' argument
 * to use OR between meta- and taxonomy query parts.
 * use '_meta_or_tax' => true in wp_query array
 */
add_filter( 'posts_where', function( $where, \WP_Query $q ){
	$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;
		$field = 'ID';// Primary id column
		$sql_tax = get_tax_sql(  $tax_args,  $wpdb->posts, $field );// Tax query
		$sql_meta = get_meta_sql( $meta_args, 'post', $wpdb->posts, $field );// Meta query
		// 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;
}, PHP_INT_MAX, 2 );

使用方式则是在 WP_Query 的参数数组里面添加一条'_meta_or_tax' => true,简单的举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$args = array(
	'post_status'			=> 'publish',
	'order'					=> 'ASC',
	'nopaging'				=> true,
	'_meta_or_tax'			=> true, //用于支持 tax_query OR meta_query 查询
	'tax_query'				=> array(
		'relation'		=> 'OR',
		array(
			'taxonomy'	=> 'category',
			'field'		=> 'id',
			'terms'		=> array(1,2,3),
			'operator'	=> 'IN'
		), 
	),
	'meta_query'			=> array(
		array(
			'key'		=> 'Headline',
			'value'		=> ''
			'compare'	=> '!='
		),
	)
);
$query = new WP_Query( $args );

这可能是一个非常小众的需求,但是用起来还是非常的爽,而且对于有相关功能需求的来说,以及用两次循环甚至三次循环来搞定简直不要不要的,子凡我要的就是最极简最极致的功能,也要最简单高效的代码。

更多关于 WordPress 优化及疑问可以添加 QQ 群:255308000

除非注明,否则均为泪雪网原创文章,禁止任何形式转载

本文链接:https://zhangzifan.com/wordpress-wp_query-tax_query-or-meta_query.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值