admin管理员组文章数量:1404561
On my site, I want some pages to not be queriable by the search form (so they don't appear when I've got something like www.ex/?s=banana)
Is there a way to "Remove" pages from the search results page (without just blindly do a condition of if is_page(id), display:none)
On my site, I want some pages to not be queriable by the search form (so they don't appear when I've got something like www.ex/?s=banana)
Is there a way to "Remove" pages from the search results page (without just blindly do a condition of if is_page(id), display:none)
Share Improve this question edited Oct 9, 2012 at 13:26 mrwweb 10.3k5 gold badges40 silver badges75 bronze badges asked Oct 9, 2012 at 12:59 Fredy31Fredy31 8782 gold badges16 silver badges31 bronze badges2 Answers
Reset to default 17In WP_Query() there is a 'post__not_in' argument where you can exclude specific post ID's.
You would create a new WP_Query inside of your search.php and use the current $query_args, then add on your 'post__not_in'.
If you wanted to make it more dynamic, you could also build in some post meta where you could do a meta query and exclude all that have "exclude" checked. (look up 'register_meta_box_cb' in register_post_type ).
For example,
add_action('pre_get_posts','wpse67626_exclude_posts_from_search');
function wpse67626_exclude_posts_from_search( $query ){
if( $query->is_main_query() && is_search() ){
//Exclude posts by ID
$post_ids = array(7,19,21);
$query->set('post__not_in', $post_ids);
}
}
To exclude all pages from search results (i.e. without having to manually supply page IDs), here's an improved version of @EricHolmes's function:
add_action( 'pre_get_posts', 'wpse67626_exclude_pages_from_search' );
function wpse67626_exclude_pages_from_search( $query ) {
// Manually supply Post/Page IDs to exclude from search results
// $exclude_page_ids = array( 7, 19, 21 );
// Or just get all page IDs
$exclude_page_ids = get_all_page_ids();
if (
!$query->is_admin &&
$query->is_search &&
$query->is_main_query() &&
!empty( $exclude_page_ids )
) {
$query->set( 'post__not_in', $exclude_page_ids );
}
}
More info:
- https://developer.wordpress/reference/hooks/pre_get_posts/
- https://developer.wordpress/reference/functions/get_all_page_ids/
- https://developer.wordpress/reference/classes/wp_query/#post-page-parameters
(ALTERNATIVE) Although, given what you are doing, you could just set exclude_from_search
for the page
post type to true
, which to me seems to be the best way to exclude a post type from search. See @prettyboymp's answer for that.
More info:
- https://developer.wordpress/reference/functions/register_post_type/
- https://codex.wordpress/Function_Reference/register_post_type
本文标签: Remove some pages from search
版权声明:本文标题:Remove some pages from search 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744843803a2628081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论