Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.com/?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

2 Answers 2

up vote 9 down vote accepted

In 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);
    }

}
share|improve this answer
3  
+1. Would add that if the posts you are excluding belong to a particular post type then you can exclude them from search when you register_post_type –  Stephen Harris Oct 9 '12 at 13:25
    
Thanks for adding the example, Stephen! –  Eric Holmes Oct 9 '12 at 13:26

To exclude all pages from search results (i.e. without having to manually supply page IDs) simply modify @EricHolmes's function like so:

add_action( 'pre_get_posts', 'wpse67626_exclude_posts_from_search' );
function wpse67626_exclude_posts_from_search( $query ) {
    if ( $query->is_main_query() && $query->is_search() ) {

        // Get an array of all page IDs with `get_all_page_ids()` function
        $query->set( 'post__not_in', get_all_page_ids() );

    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.