I came across a need where I was searching for a possible array of options within a multi select. I will post my solution but curious if there was an easier/ cleaner way to do it — so looking for either a better solution, or feedback on my solution
First, an example of the setup and need
user has a list of favorite colors (red / orange / yellow / green / blue / violet)
user can choose 3, so he selects (yellow / green / blue)
I need to find users who like primary colors (red / yellow / blue)
at first I thought a simple IN search with array for value would fill my need, but I later realized that the array of user selections was stored as a serialized string in the database, so it wasn’t finding my people
What I came up with is this
$cpt_query = array('relation' => 'OR'); // doing an or query, because we want people who like one of the colors, not all of the colors
foreach($_POST['cpt_query'] as $selection) {
$cpt_query[] = array(
'key' => 'people_color', // this is where they have their color stored
'value' => '"' .$selection . '"', // stored as serialized, so surrounded by quotes, stops a false true for bluegreen if searching "blue" by surrounding it by quotes
'compare' => 'LIKE'
);
}
$args = array(
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'people', // custom post type of people
'meta_query' => array(
'relation' => 'AND',
$cpt_query,
array(
'key' => 'people_type', // other value we are searching for, but this is a 1 to 1
'value' => $_POST['type'],
'compare' => 'LIKE'
)
)
);
$posts = get_posts( $args );