在里面wp_postmeta
我有一个meta\\u键,它存储冒号分隔的字符串,例如“CA:Georgia:NY”。
因此,对于meta\\u key=\'state\',可以有以下几个条目:
对于post 1=“CA:乔治亚州:纽约”
对于post 2=“CA”
对于post 3=“格鲁吉亚:CT”
对于post 4=“WA:CA”
我想查询一下meta\\u键包含“CA”或“Georgia”的所有帖子。
我动态构建WP\\u查询参数。
$statelist = array();
$args = array(
\'post_type\' => \'post\',
\'meta_query\' => array(
\'relation\' => \'OR\')
);
if($_GET[\'state\'] != NULL)
{
$state_arr = explode( \',\', $_GET[\'state\']);
for($i=0; $i<count($state_arr); $i++)
{
//tried also with relation = OR for first entry
$current_arr = array(\'relation\' => \'OR\' ,
array(
\'key\' => \'state\',
\'value\' => $state_arr[$i],
\'compare\' => \'LIKE\'
));
array_push($statelist, $current_arr);
}
}
if(count($statelist) >= 1)
array_push($args[\'meta_query\'], $statelist);
但我总是得到如下查询:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
WHERE 1=1
AND ((((wp_postmeta.meta_key = \'state\'
AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%Georgia%\')) **
AND** ((mt1.meta_key = \'state\'
AND CAST(mt1.meta_value AS CHAR) LIKE \'%CA%\'))))
AND wp_posts.post_type = \'post\'
AND (wp_posts.post_status = \'publish\'
OR wp_posts.post_status = \'private\')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC LIMIT 0,
50
因此,此查询只接收Post 1=“CA:乔治亚州:纽约”
虽然我想要所有的帖子meta_key=\'state\'
有“CA”或“Georgia”。尽管显式创建了具有关系的数组OR
它正在切换到默认值AND
.
构建Query
争论?如果专家们能提供一些线索,那就太好了。
最合适的回答,由SO网友:Sumit 整理而成
您的参数结构不正确。应该是这样的
[meta_query] => Array
(
[0] => Array
(
[key] => state
[value] => a
[compare] => LIKE
)
[1] => Array
(
[key] => state
[value] => b
[compare] => LIKE
)
[2] => Array
(
[key] => state
[value] => c
[compare] => LIKE
)
[relation] => OR
)
但它就像
[meta_query] => Array
(
[relation] => OR
[0] => Array
(
[0] => Array
(
[relation] => OR
[0] => Array
(
[key] => state
[value] => a
[compare] => LIKE
)
)
[1] => Array
(
[relation] => OR
[0] => Array
(
[key] => state
[value] => b
[compare] => LIKE
)
)
[2] => Array
(
[relation] => OR
[0] => Array
(
[key] => state
[value] => c
[compare] => LIKE
)
)
)
)
以这种方式更改代码以匹配建议的结构
$statelist = array();
$args = array(
\'post_type\' => \'post\',
\'meta_query\' => array(
\'relation\' => \'OR\')
);
if($_GET[\'state\'] != NULL)
{
$state_arr = explode( \',\', $_GET[\'state\']);
for($i=0; $i<count($state_arr); $i++)
{
//tried also with relation = OR for first entry
$current_arr = array(
\'key\' => \'state\',
\'value\' => $state_arr[$i],
\'compare\' => \'LIKE\'
);
array_push($statelist, $current_arr);
}
}
if(count($statelist) >= 1) {
$statelist[\'relation\'] = \'OR\';
$args[\'meta_query\'] = $statelist;
}
参考号:
https://codex.wordpress.org/Class_Reference/WP_Meta_Query