Home › Forums › ACF PRO › Filtering by relationship field in pre_get_posts on post archive page › Reply To: Filtering by relationship field in pre_get_posts on post archive page
Hmmm, spoke too soon. My code now works fine on post archive pages, but I need to add it to the CPT “events” as well, which uses the exact same set of custom fields. But this isn’t working. I can test and see that it is correctly triggering the various if statements, but it doesn’t seem that the meta query gets applied – it just returns all results, unfiltered. Posts are still working, though, with the exact code below. Does this sort of meta query get applied differently to a CPT than to the standard post?
function query_by_relationship( $query ) {
if( is_admin() ) {
return $query;
}
if ((is_archive() && $query->is_main_query()) || ( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'events' ) ) {
if( isset($_GET['sector']) ) {
$meta_query = array(
array(
'key' => 'related_industries',
'value' => '"' . $_GET['sector'] . '"',
'compare' => 'LIKE',
)
);
$query->set('meta_query', $meta_query);
} else if( isset($_GET['pa']) ) {
$meta_query = array(
array(
'key' => 'related_practice_areas',
'value' => '"' . $_GET['pa'] . '"',
'compare' => 'LIKE',
)
);
$query->set('meta_query', $meta_query);
} else if( isset($_GET['lawyer']) ) {
$meta_query = array(
array(
'key' => 'related_people',
'value' => '"' . $_GET['lawyer'] . '"',
'compare' => 'LIKE',
)
);
$query->set('meta_query', $meta_query);
}
}
// return
return $query;
}
add_action('pre_get_posts', 'query_by_relationship');
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!
ACF wouldn’t be so widely used in WordPress if it didn’t have some pretty amazing capabilities. In this article, we look at a few of the features we’ll discuss during “7 things you didn’t know you could do with ACF” at #WPEDecode later this month. https://t.co/5lnsTxp81j pic.twitter.com/Yf0ThPG1QG
— Advanced Custom Fields (@wp_acf) March 16, 2023
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.