Home › Forums › General Issues › Filtering issues which removes wordpress navigation
I have the following code in my functions.php file which allows me to query posts in my custom post type named ‘jobs’ and filter them where an ACF field named ‘bracket’ matches a certain value. It works fine, but when the page loads and i see the url appended such as ‘/jobs/?bracket=20-30’ my wordpress navigation menu items aren’t present on the page. I can’t understand whats wrong?
Here is my functions.php code:
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query )
{
// bail early if is in admin
if( is_admin() )
{
return;
}
// get meta query
$meta_query = $query->get('meta_query');
// initialize meta query as empty array if not set
if ( ! is_array( $meta_query ) ) {
$meta_query = array();
}
// continue if not found in url
if( isset($_GET[ 'bracket' ]) )
{
// append meta query
$meta_query[] = array(
'key' => 'bracket',
'value' => $_GET['bracket'],
'compare' => '=',
);
}
// update meta query
$query->set('meta_query', $meta_query);
return;
}
The problem is that your query changes are added to every query and you need to narrow that down.
The first thing to check is that it is the main query done by WP
if (!$query->is_main_query()) {
return;
}
The next thing you have to do is make sure that the query is being done only for your CPT
if (!isset($query->query_vars) ||
!isset($query->query_vars['post_type']) ||
$query->query_vars['post_type'] != 'YOUR POST TYPE') {
return;
}
Add the two if statements to the top of your function, change ‘YOUR POST TYPE’ to ‘jobs’ after your if statement to check is_admin()
Thanks. Yes, that results in my nav menu showing again, but now my filter does not work. The url is appended as like so ‘/jobs/?bracket=30-40’ but it shows ALL posts belonging to my custom post type not just the ones where the ACF field for ‘bracket’ equals 30-40.
You must be logged in to reply to this topic.
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!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?
— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 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.