Support

Account

Home Forums General Issues Filtering issues which removes wordpress navigation

Solving

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;
    }
    
  • This reply has been marked as private.
  • Could you provide me with the complete code i need?

  • 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.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.