Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am writing some PHP which allows users of my site to submit a form and query posts by their post_meta. Everything works fine except for one thing, I used Advanced Custom Fields to create the post_meta and ACF saves meta values as a serialized array. I need to keep the data in this format so ACF can pre-fill the custom fields in the admin panel. I need a way to compare an array of values (the user selects via checkboxes in the form) to a serialized array in the database. The first part of my query looks like the following, with $amenities being the array of checkbox values:

$the_query = new WP_Query(
    array(
        'post_type' => 'listing',
        'meta_query' => array(
            array(
                'key' => 'distance',
                'value' => $distance,
                'type' => 'numeric',
                'compare' => '<='
            ),
            array(
                'key' => 'amenities',
                'value' => $amenities[0],
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'amenities',
                'value' => $amenities[1],
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'amenities',
                'value' => $amenities[2],
                'compare' => 'LIKE'
            )
        )
    )
);

The only way I can get the query to work is by querying for each possible value ($amenities[#]) the user could have entered in the checkboxes but this seems to be too cumbersome for my database to handle.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

I found a way to build a custom query that goes through the checkboxes the user selected and then adds an array for that value to the query dynamically. That way it checks to see if each value selected is in the serialized array, and then moves onto the next one. Runs a lot smoother than what I was doing before.

for ($i=0; $i< count($amenities); $i++)
    {
        $count = count($arrays);
        $arrays[$count] = array(
                    'key' => 'amenities',
                    'value' => $amenities[$i],
                    'compare' => 'LIKE'
                    );
    }

$the_query = new WP_Query(array(
        'post_type' => 'listing',
        'post_status' => 'publish', 
        'category_name' => 'private_rental',
        'meta_query' => $arrays
    ));
share|improve this answer
add comment

protected by toscho Sep 12 '13 at 10:06

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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