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 |1 Answer
Reset to default 1I 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
版权声明:本文标题:Search page doesn't recognise post_type=page 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736634011a1945838.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
get_posts
/query_posts
/WP_Query
? Or making modifications to the$wp_query
object? Note thats=post_type=page
isn't a valid URL get parameter ass
is missing a value and there is no&
to indicate a second URL parameter – Tom J Nowell ♦ Commented Feb 28, 2024 at 13:46/?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 whypage
doesn't. – evilscary Commented Feb 28, 2024 at 16:46pre_get_posts
filters in your codebase? – Tom J Nowell ♦ Commented Feb 28, 2024 at 16:50