如何在“tax_query”和“ meta_query”中添加“OR”关系。因为默认为“AND”
[query] => Array
(
[relation] => OR
[posts_per_page] => 3
[offset] => 0
[orderby] => post_date
[order] => DESC
[post_type] => biography
[post_status] => publish
[meta_query] => Array
(
[relation] => OR
[0] => Array
(
[key] => f_name
[value] => gh
[compare] => LIKE
)
[1] => Array
(
[key] => l_name
[value] => gh
[compare] => LIKE
)
)
[tax_query] => Array
(
[relation] => OR
[0] => Array
(
[taxonomy] => historical-period
[field] => term_id
[terms] => Array
(
[0] => 27
)
[operator] => IN
)
)
)
我们得到了以下结果
结果
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (27))
**AND **
(( wp_postmeta.meta_key = 'f_name' AND wp_postmeta.meta_value LIKE '%gh%' ) OR ( wp_postmeta.meta_key = '%gh%' )) AND wp_posts.post_type = 'biography' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 3
我们需要以下结果
结果
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (27))
**OR**
(( wp_postmeta.meta_key = 'f_name' AND wp_postmeta.meta_value LIKE '%gh%' ) OR ( wp_postmeta.meta_key = '%gh%' )) AND wp_posts.post_type = 'biography' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 3
请帮助在“tax_query”和“ meta_query”之间添加“或”关系
我也试过下面的代码。但是我们没有得到一个准确的结果。
1.过滤器_查询
add_filter('get_meta_sql', 'filter_query', 10, 1);
$posts = new WP_Query($post_args);
remove_filter('get_meta_sql', 'filter_query');
function filter_query($sql){
$pos = strpos($sql['where'], 'AND');
if ($pos !== false) {
$sql['where'] = substr_replace($sql['where'], 'OR', $pos, strlen('AND'));
}
return $sql;
}
参考链接:
How to give OR relation in tax_query and meta_query Wordpress
问题:
如果我们使用上面的代码,它会在整个查询中添加“OR”关系,包括 meta_key和meta_value关系。
1.手动合并查询到的帖子
$photos_query = new WP_Query( $photos );
$quotes_query = new WP_Query( $quotes );
$result = new WP_Query();
// start putting the contents in the new object
$result->posts = array_merge( $photos_query->posts, $quotes_query->posts );
// here you might wanna apply some sort of sorting on $result->posts
// we also need to set post count correctly so as to enable the looping
$result->post_count = count( $result->posts );
**问题:**如果我们使用上面的代码,我们会发现很多重复的结果。并且花费了很多时间。有时它不返回结果是因为查询执行会话超时。
参考链接:
https://wordpress.stackexchange.com/questions/71576/combining-queries-with-different-arguments-per-post-type/71582#71582
1条答案
按热度按时间ny6fqffe1#
SQL语句: