I have a custom post type called “on-air” that included a custom-field called “daysonair”. The form for this has checkboxes for each day of the week.
When you add/update a post, the checked items are stored as an array in the custom-field.
I can’t figure out how to add that custom-field to my WP_Query() search:
array( 'key' => 'daysonair', 'value' => 'Thursday', 'compare' => 'IN' )
I’ve tried numerous types of comparisons with no luck.
The data in the database is:
Where all the weekdays have been checked. I’m just looking to see if Thursday is in the array.
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Searching inside a serialized array is difficult and inefficient– ie. slow. The following pure SQL will do it:
SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE 'daysonair' AND `meta_value` LIKE '%thursday%' LIMIT 0 , 100
Something like this should get
WP_Query to do something similar:
$args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'daysonair', 'value' => 'thursday', 'compare' => 'LIKE', ) ) ); $q = new WP_Query($args); var_dump($q);
LIKE queries with wildcards–
%— are very slow. The query has to check every row in the table for a match.
Additionally, this will be prone to error as any occurance of “thursday” will match, for example, something in an attachment image
The problem is that a serialize string is a PHP construct. MySQL does not know what to do with it other than treat it like any other string.
The only really good fix, and I don’t know if it possible in you case, is to change how the data is stored in the database. If you need to search the data it should not be stored as a serialized string. Each piece of data should be stored as an independent key/value pair.
A custom LIKE query will sort of work, but I personally wouldn’t trust it for anything other than the simplest implementation (as s_ha_dum said in the comments).
$args = array( 'tax_query' => array( array( 'taxonomy' => 'days_of_week', 'field' => 'slug', 'terms' => 'wednesday' ) ) ); $query = new WP_Query( $args );