It’s a bit of a hack, but…
So begins practically every solution I find regarding WordPress issues. Here’s another one. I wanted to query posts by meta_value but the data, generated by Advanced Custom Fields, is in serialised array form in the database table.
Searching for a general solution for what must be a common problem came up with unsatisfactory options (https://wordpress.org/support/topic/custom-query-filtered-by-meta_value-that-is-an-array). Basically, omitting the troublesome parameter from the query and subsequently omitting those posts by using PHP’s in_array function.
The major problem with that approach is if you’re paginating the results, and your query is getting 10 posts per page, the omitting posts after the query will result in random numbers of posts on the page, potentially even zero posts. Totally unworkable.
I thought there might exists a WordPress method to cover such a likely scenario. The nasty hack that I came up with was to search for the string I wanted within the serialised data [ick].
$args = array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array (
'key' => 'my_key',
'value' => '"'.$target_value.'"',
'compare' => 'LIKE'
$new_query = new WP_Query( $args );
This results in a query containing:
This may not work in all instances, but I was searching on a numeric key with corresponded to a related post added with ACF so for my application it’s pretty robust, despite being a horrible, horrible hack.