0

This code is working fine but when I add multiple commas separated values in custom fields value then It's not working. (Example:- Demo, Demo Two)

$meta_query = array('relation' => 'AND');
if ($Style_Cabinet_Style)
 {
    $meta_query[] =  array(
        'meta_key' => 'Cabinet_Style',
        'value' => $Style_Cabinet_Style,
        'compare' => 'IN'
        );



$query = new WP_Query(
array( 
    'post_type' => 'gallery',
    'meta_query' => $meta_query,
)
);
0

It's not supposed to. If you want to use multiple values in an IN meta query you need to pass an Array. That would look like this:

$Style_Cabinet_Style = array( 'Demo', 'Demo Two' );

If you only have a String with commas separating the values, eg. 'Demo, Demo Two'. Then you can use explode() to split the values into an array using commas:

$Style_Cabinet_Style = 'Demo, Demo Two'; // Assuming

$values = explode( ',', $Style_Cabinet_Style );
$values = array_map( 'trim', $values );

The array_map() line is running the trim() function on all the values in the array. This removes whitespace from the beginning and end of the value. This ensures that any spaces between the commas, eg. 'One, Two, Three' are removed after splitting into an array, otherwise you'd end up with:

$values = array( 'Demo', ' Demo Two' );

Once you've done that you can pass the values to the meta query:

$meta_query = array( 'relation' => 'AND' );

if ( $Style_Cabinet_Style ) {
    $values = explode( ',', $Style_Cabinet_Style );
    $values = array_map( 'trim', $values );

    $meta_query[] =  array(
        'meta_key' => 'Cabinet_Style',
        'value'    => $values,
        'compare'  => 'IN'
    );

    $query = new WP_Query(
        array( 
            'post_type' => 'gallery',
            'meta_query' => $meta_query,
        )
    );
}
|improve this answer|||||
  • Hii @jacob, Thanks for your help. I tried your codes it but 'value' is not matching multiple commas separated values by custom fields. – Siddharth Nov 14 '18 at 13:13
  • See how I put multiple values (prntscr.com/li9kpe). – Siddharth Nov 14 '18 at 13:17
  • Well that's not multiple values. That's just a value with a comma in it. You can't query inside values like that. – Jacob Peattie Nov 14 '18 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.