Finding posts containing matching array elements in a meta field usign WP_Query

I have a metafield, that contains a series of options and writes the results to an array in a single meta field:

array([0]=>'First',
      [1]=>'Second',
      [2]=>'Third',
     );

I find posts that contain any of the array elements, and display them using WP_Query

Read More
$search = new WP_Query('meta_key=mykey&meta_value=second');

But this doesn’t seem to work. Any idea on how to achieve this?


I have edited my method, following this question:

$arg['meta_key'] == $key;
$args['meta_value'] = "%|".$value."|%";
$custom_query = new WP_Query($args);

But no darts.

Related posts

Leave a Reply

2 comments

  1. I believe you have to use meta compare LIKE. If you do a regular meta query, the resulting SQL will be meta_value = your_value, which is never going to find anything because it’s trying to match the entire contents of the field.

  2. I’m pretty sure to return or search an array for values (or keys) you need to use meta_query

    So something like:

    $search = array(
               'post_type' => 'post',
               'meta_query' => array(
                                    array(
                                       'key'     => 'mykey',
                                       'value'   => 'second',
                                         )
                                    )
                    );
    
     $query = new WP_Query($search);