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.
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.