First of all, I know it’s a duplicate, but none of the older answers were helpful.

I’m searching in posts through post_meta. Here’s my code, which currently returns nothing.

$args   =   array(
    'numberposts'   => -1,
    'post_type'     => 'post',
    'meta_query'    => array(
        array(
            'key'       => 'system_power_supply',
            'value'     => array('single', 'redundant'),
            'compare'   => 'IN',
        )
    )

);

$query = new WP_Query($args);
echo $query->found_posts;

If I remove meta_query it works. I’m sure of these things:

  • There’s no spelling mistake in the key or the value.
  • post type is post
  • There is a post with the value ‘single’ in ‘system_power_supply’. However, post fields are generated by Advanced Custom Fields.

2

There’s no easy way to search serialized values in a meta query. If the list of values isn’t crazy long, potentially you could set up multiple meta queries:

'meta_query'    => array(
    'relation' => 'OR',
    array(
        'key'       => 'system_power_supply',
        'value'     => 'single',
        'compare'   => 'LIKE',
    ),
    array(
        'key'       => 'system_power_supply',
        'value'     => 'redundant',
        'compare'   => 'LIKE',
    )
)

Or if you wanted to get super fancy, you could set it up dynamically:

$values_to_search = array('single', 'redundant');
$meta_query = array('relation' => 'OR');
foreach ($values_to_search as $value) {
    $meta_query[] = array(
        'key'       => 'system_power_supply',
        'value'     => $value,
        'compare'   => 'LIKE',
    );
}

Leave a Reply

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