meta_query – check for multiple meta values in key which holds an array of values
In my application, I have two custom post types: ‘session’ and ‘speaker’. For the ‘session’ post type, I have added a custom field ‘_session_speakers’ which stores an array of one or more ‘speaker’ post type ids associated with the post. So the meta_value for the ‘_session_speakers’ meta_key looks something like this:
a:2:{i:0;s:2:"40";i:1;s:2:"15";}
I’m trying to implement a speaker search so users can search for all sessions by a particular speaker. I can get an array of speaker ids that match the search keyword as follows:
$speaker_args = array(
'numberposts' => -1,
'posts_per_page' => -1,
'post_type' => 'speaker',
'post_status' => 'publish',
'fields' => 'ids',
's' => $keyword
);
$speaker_ids = get_posts($speaker_args);
Then I’d like to take that array and query the session posts to find all sessions that have any of the speaker ids in the ‘_session_speakers’ field. I’ve tried the following, but it does not return any results even though $speaker_ids contains values:
$args = array(
'numberposts' => -1,
'posts_per_page' => -1,
'post_type' => 'session',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
'search_clause' => array(
'key' => '_session_speakers',
'value' => $speaker_ids,
'compare' => 'IN'
)
)
);
$sessions = new WP_Query($args);
Any thoughts on how I can accomplish this?
Leave an answer