我需要搜索property
post类型,在不是主查询的常规WP\\U查询中,但我需要能够搜索值LIKE
在以下任何meta\\u查询中,也需要搜索LIKE
在tax\\u查询中,但tax\\u查询和meta\\u查询之间的比较不应是AND
, 它需要是一个OR
. 如何做到这一点?以下是我的WP\\u查询参数的设置方式,但它不会在应该返回的地方返回任何结果:
array (
\'post_type\' => \'property\',
\'posts_per_page\' => 10,
\'post_status\' => \'publish\',
\'tax_query\' =>
array (
\'relation\' => \'OR\',
0 =>
array (
\'taxonomy\' => \'type\',
\'field\' => \'name\',
\'terms\' => \'Strip\',
),
),
\'meta_query\' =>
array (
\'relation\' => \'OR\',
0 =>
array (
\'key\' => \'city\',
\'value\' => \'Strip\',
\'compare\' => \'LIKE\',
),
1 =>
array (
\'key\' => \'state\',
\'value\' => \'Strip\',
\'compare\' => \'LIKE\',
),
2 =>
array (
\'key\' => \'salelease\',
\'value\' => \'Strip\',
\'compare\' => \'LIKE\',
),
3 =>
array (
\'key\' => \'zip\',
\'value\' => \'Strip\',
\'compare\' => \'LIKE\',
),
),
)
Strip
是否将搜索词发送到
value
. 我有一个
type
名称为
Strip Centers
, 但我这里的结果是空的。我认为这是使用AND来将类型与所有meta\\u查询进行比较。我只想要任何类型的值
OR
meta\\u查询的任何值。
如何正确执行此操作?
最合适的回答,由SO网友:86Dev 整理而成
查看WP\\u Query使用的WP\\u Tax\\u Query和WP\\u Meta\\u Query,它们返回各自带有and关系的where子句,并且没有用于更改该行为的hook或$args。
此外,tax\\u查询是在主查询的其余部分之前计算的,因此它包含在term_taxonomy_id IN (...)
类型此外,WP\\u Tax\\u查询不接受LIKE运算符(see doc)
您可以在中查看最终查询WP_Query->request
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 (1))
AND ( ( wp_postmeta.meta_key = \'city\' AND wp_postmeta.meta_value LIKE \'%Strip%\' )
OR ( wp_postmeta.meta_key = \'state\' AND wp_postmeta.meta_value LIKE \'%Strip%\' )
OR ( wp_postmeta.meta_key = \'salelease\' AND wp_postmeta.meta_value LIKE \'%Strip%\' )
OR ( wp_postmeta.meta_key = \'zip\' AND wp_postmeta.meta_value LIKE \'%Strip%\' ) )
AND wp_posts.post_type = \'post\'
AND ((wp_posts.post_status = \'publish\'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC LIMIT 0, 10
解决您的问题的方法是使用
$wpdb
获取与搜索值匹配的所有帖子ID,然后将其转换为WP\\u Post objects数组。
function search_posts($value)
{
global $wpdb;
$value = \'%\'.$wpdb->esc_like($value).\'%\';
$sql = $wpdb->prepare("SELECT p.ID
FROM {$wpdb->prefix}posts p
LEFT JOIN {$wpdb->prefix}postmeta m ON m.post_id = p.ID
LEFT JOIN {$wpdb->prefix}term_relationships r ON r.object_id = p.ID
LEFT JOIN {$wpdb->prefix}term_taxonomy tt ON tt.term_taxonomy_id = r.term_taxonomy_id AND tt.taxonomy = \'type\'
LEFT JOIN {$wpdb->prefix}terms t ON t.term_id = tt.term_id
WHERE p.post_status = \'publish\' AND p.post_type = \'property\'
AND ((m.meta_key = \'city\' AND m.meta_value LIKE %s)
OR (m.meta_key = \'state\' AND m.meta_value LIKE %s)
OR (m.meta_key = \'salelease\' AND m.meta_value LIKE %s)
OR (m.meta_key = \'zip\' AND m.meta_value LIKE %s)
OR (t.name LIKE %s))
GROUP BY p.ID", $value, $value, $value, $value, $value);
$ids = $wpdb->get_col($sql);
if (is_array($ids) && count($ids) > 0)
return array_map(\'get_post\', $ids);
else
return []; // or whatever you like
}