admin管理员组

文章数量:1125966

I've created some custom filter buttons for my search page, listing various custom post_types. Included in the list is the basic 'page' post_type. However, when I use this filter (updating the url to /?s=test&post_type=page for e.g.) this doesn't seem to be included in the default WP_Query being run on the page.

If I print_r($wp_query) I can see every other post_type being mirrored in the query. However when post_type=page is passed, the query doesn't pick it up.

Is this usual behavior? If so, how can I make the search page only return pages, not posts?

I've created some custom filter buttons for my search page, listing various custom post_types. Included in the list is the basic 'page' post_type. However, when I use this filter (updating the url to /?s=test&post_type=page for e.g.) this doesn't seem to be included in the default WP_Query being run on the page.

If I print_r($wp_query) I can see every other post_type being mirrored in the query. However when post_type=page is passed, the query doesn't pick it up.

Is this usual behavior? If so, how can I make the search page only return pages, not posts?

Share Improve this question edited Feb 28, 2024 at 16:44 evilscary asked Feb 28, 2024 at 11:43 evilscaryevilscary 1114 bronze badges 4
  • 2 are you creating a brand new query to customize what's on the search pages template based on your filters viaget_posts/query_posts/WP_Query? Or making modifications to the $wp_query object? Note that s=post_type=page isn't a valid URL get parameter as s is missing a value and there is no & to indicate a second URL parameter – Tom J Nowell Commented Feb 28, 2024 at 13:46
  • @TomJNowell edited. The URL being passes is actually /?s=test&post_type=page. I'm not creating a new search query, just trying to patch into the existing one. Passing any other post_type in the URL works, I can't work out why page doesn't. – evilscary Commented Feb 28, 2024 at 16:46
  • do you have pre_get_posts filters in your codebase? – Tom J Nowell Commented Feb 28, 2024 at 16:50
  • @TomJNowell no, I don't – evilscary Commented Feb 29, 2024 at 9:04
Add a comment  | 

1 Answer 1

Reset to default 1

I found a solution in this answer here: https://stackoverflow.com/questions/63678063/wordpress-search-filtering-pages-and-posts

I customised the function as follows:

function page_search_filter( \WP_Query $query ) {
    if ( ! is_admin() ) {
        if ( $query->is_main_query() && $query->is_search() ) {
            if ( isset( $_GET['post_type'] ) && $_GET['post_type'] == 'page' ) {
                $query->set( 'post_type','page' );
            }
        }
    }
    return $query;
}
add_action( 'pre_get_posts', 'page_search_filter' );

本文标签: Search page doesn39t recognise posttypepage