欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress 自定义 WP_Query 循环如何支持 tax_query or meta_query 参数

作者 : 自学哈 本文共1909个字,预计阅读时间需要5分钟 2022-11-26 共99人阅读
也想出现在这里? 联系我们

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

子凡最近为了满足泪雪网的功能需求,查找了大量的教程,甚至想过用两个 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 );

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

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress 自定义 WP_Query 循环如何支持 tax_query or meta_query 参数
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号