• I have added a custom taxonomy named “area” to the default “post” post type. It’s meant to organize posts by geographical area.

    In category pages I’ve added a dropdown that allows the user to filter the posts by area. I do this by adding a URL parameter named “area-filter” to the URL of the category. Then using the pre_get_posts filter I change the query

    add_action('pre_get_posts', 'my_pre_get_posts');
    /**
     * @param WP_query $query
     */
    function my_pre_get_posts( $query ) {
    
        if ($query->is_main_query() && !is_admin() && isset( $_GET['area-filter'] ) && is_numeric($_GET['area-filter']) && $_GET['area-filter']!= 0) {
    
            $queryArray = array('relation' => 'AND');
    
            if (isset( $_GET['area-filter'] )) {
                $queryArray[] = array(
                    'taxonomy' => 'area',
                    'terms'    => $_GET['area-filter'],
                    'operator' => 'IN'
                );
            }
    
            $query->set('tax_query', $queryArray);
    
        }
    
    }

    Everything works well on category pages. But if I try to do the same on archive pages I get a 404 result. This is expected behavior, as WordPress doesn’t want empty archive pages to be indexed. However, my users reach this page by using the filter and I want them to stay in the archive template and just show them a “No posts found” message.

    Is there any way by which I can achieve this result?

  • The topic ‘How to prevent 404 when using pre_get_posts to filter an archive page’ is closed to new replies.