在wp_Query的$args中获取错误的关系值?

时间:2016-08-26 作者:user101703

我正在尝试从数据库中获取自定义插件和帖子类型的数据。我的查询参数应如下所示:

$args = array(
    \'post_type\'  => \'products\',
    \'post_status\'=> \'publish\',
    \'meta_query\' => array(
       \'relation\' => \'OR\',
      array( \'key\'=>\'product_commercial\',
       \'value\'=>\'on\',
       \'compare\'=>\'=\'  
    ), 
      array( \'key\'=>\'product_exterior\',
       \'value\'=>\'on\',
       \'compare\'=>\'=\'  
    )
)
);
$search_query = new WP_Query( $args );
But, 我正在尝试动态添加元键值,如:

$inner_arrays=array();
$count = 0;
foreach($values as $value){
if($value){

        $inner_arrays[$count][\'key\'] .= $value;
        $inner_arrays[$count][\'value\'] .= \'on\';
        $inner_arrays[$count][\'compare\'] .= \'=\';
        echo $count++;
}
}
print_r($inner_arrays);
    //$array =  $array[0] ; 
    $args = array(
    \'post_type\'  => \'products\',
    \'post_status\'=> \'publish\',
    \'meta_query\' => array(
       \'relation\' => \'OR\',
    $inner_arrays
)
);
//values are some random values (say fetched from db).
现在,当我使用打印查询时

echo "<pre>Last SQL-Query: {$search_query->request}".\'<br/>\';
它显示

    Last SQL-Query: 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 )  INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1  AND ( 
  ( 
    ( wp_postmeta.meta_key = \'product_commercial\' AND CAST(wp_postmeta.meta_value AS CHAR) = \'on\' ) 
    **AND** 
    ( mt1.meta_key = \'product_framed\' AND CAST(mt1.meta_value AS CHAR) = \'on\' ) 
    **AND** 
    ( mt2.meta_key = \'product_horizontal\' AND CAST(mt2.meta_value AS CHAR) = \'on\' )
  )
) AND wp_posts.post_type = \'products\' AND ((wp_posts.post_status = \'publish\')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
PROBLEM: 我正在使用relation => OR, 但是AND 在SQL查询中。我做错了什么?

1 个回复
SO网友:Esar-ul-haq Qasmi

添加:$inner_arrays[\'relation\'] = \'OR\';然后查询将如下所示:

$args = array(
    \'post_type\'  => \'products\',
    \'post_status\'=> \'publish\',
    \'meta_query\' => $inner_arrays
);
这很有效……)