I’ve asked a related question previously, but I think I’ve finally worked out the crux of my issue.
I’m using Advanced Custom Fields and have a number of custom fields attached to my post type. I’m trying to alter the URL to receive posts via their custom field and value.
And I’m getting really close. This is what’s currently in my functions.php:
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts( $query ) {
if( is_admin() ) { return; }
$meta_query = $query->get('meta_query'); // get original meta query
if( isset($_GET['type']) ) {
$type = '"' . $_GET['type'] . '"';
$meta_query[] = array(
'key' => 'type',
'value' => $type,
'compare' => 'LIKE',
);
}
$query->set('meta_query', $meta_query); // update the meta query args
return; // always return
}
Now because ACF uses serialized arrays when dealing with multiple values in custom fields, I’m using the LIKE
query. The type
custom field actually accepts multiple values, and I’m able to display posts by one type
(i.e: women) successfully.
website.com?type=women
But when trying to retrieve multiple type
s (i.e: women,men,boys), this doesn’t work.
website.com?type=women,men,boys
Now I realise I’m working with serialized arrays here, and if I wanted it to query multiple type
‘s I’d have to explode that $type
variable, but that doesn’t seem to be working either.
If anyone can help, I’m desperate for a solution. Thanks!
EDIT | Multiple times for each type:
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'type',
'value' => 'men',
),
array(
'key' => 'type',
'value' => 'women',
),
array(
'key' => 'type',
'value' => 'boys',
),
);
I just figured out myself how to do it
Take a look at this example:
I am getting
$tag_ids
with a normalget_results
.Then i create the first item of the array for meta_query in order to define the OR i need.
Then i iterate through the collection of objects i received from get_results and create as many arrays for the meta_query as i need.
It works like a charm.
LIKE
does not take array value. Your options probably are:OR
clause.REGEXP
compare and glue multiple types into regular expression, might be seriously slow to run.