I am trying to fetch data from the database for my custom plugin and post type.
my query arguments should be like:

$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, I am trying to add meta key values dynamically like:

$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).

Now when I print the query using

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

it displays

    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: I am using relation => OR, but getting AND in SQL query.
What am I doing wrong?

1 Answer
1

add : $inner_arrays['relation'] = 'OR';
and then query will be like :

$args = array(
    'post_type'  => 'products',
    'post_status'=> 'publish',
    'meta_query' => $inner_arrays
);

this works …. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *