Home › Forums › General Issues › Filter products/categories/ by ACF field › Reply To: Filter products/categories/ by ACF field
I have experimented a bit and I can confirm the following works for regular categories:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'id_category_mercator',
);
add_action('pre_get_terms', 'my_pre_get_terms', 10, 1);
function my_pre_get_terms( $query ) {
// bail early if is in admin
if( is_admin() ) return;
// bail early if not main query
// - allows custom code / plugins to continue working
//if( !$query->is_main_query() ) return;
// get meta query
$meta_query = $query->meta_query;
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: https://mywebsite/wp-json/wc/v3/products/category?id_category_mercator=merca1
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query->queries[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->meta_query = $meta_query;
}
You might want to figure something out to replace the commented out line of code:
//if( !$query->is_main_query() ) return;
But I don’t know what other functionality your project has that could cause/suffer conflicts.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.