Comparing arrays with meta_query in pre_get_posts

I’m working on a form for filtering a list of posts using custom fields created with the Advanced Custom Fields plugin. Because of the form, I’m using the pre_get_posts action to change the query via GET requests. (following code references are either PHP or dumped from print_r())

I set the meta_query like this:

$query->set('meta_query',$filter);

and $filter looks like this:

Array
(
    [0] => Array
        (
            [key] => delivery_method
            [value] => Array
                (
                    [0] => Online
                    [1] => Scheduled

                )

            [compare] => IN
        )
)

The custom field that I am querying is structured like this:

Array (
    [delivery_method] => Array (
        [0] => Online
        [1] => Scheduled
    )
)

When I look for posts with [compare] => IN (as above), no posts are returned. When I look for posts with [compare] => NOT IN, all of the posts are returned.

I am trying to return only those posts which have a specific “delivery method”. Is there a way to compare the two arrays that I missed? or do I have to somehow explode one of the arrays and compare individual values against an array?

2 Answers
2

The ACF Documentation recommends checking the values individually rather than simultaneously using an array.

The following code is from the ACF Documentation for the Checkbox field type:

http://www.advancedcustomfields.com/resources/field-types/checkbox/

/*
*  Query posts for a checkbox value.
*  This method uses the meta_query LIKE to match the string "red" to the database value a:2:{i:0;s:3:"red";i:1;s:4:"blue";} (serialized array)
*  The above value suggests that the user selected "red" and "blue" from the checkbox choices
*/

$posts = get_posts(array(
    'meta_query' => array(
        array(
            'key' => 'field_name', // name of custom field
            'value' => '"red"', // matches exaclty "red", not just red. This prevents a match for "acquired"
            'compare' => 'LIKE'
        )
    )
));

Therefore the query in pre_get_posts should look like this:

$filter = array(
    array(
        'key' => 'delivery_method'
        'value' => '"Online"'
        'compare' => 'LIKE'
    ),
    array(
        'key' => 'delivery_method'
        'value' => '"Scheduled"'
        'compare' => 'LIKE'
    )
)

$query->set('meta_query',$filter);

Leave a Comment