1

How can I exclude pages for logged-in members from WordPress search results?

  • 1
    Have you already searched the site? What have you tried? Where did you fail? Please edit your post with your efforts. Thanks. – kaiser Apr 29 '14 at 17:09
6

Add this to your child themes functions file using a code editor like Notepad++.

You will need to change the page I.D's in the code to your own.

Exclude Specific Pages From Search Results

add_filter( 'pre_get_posts', 'exclude_pages_search_when_logged_in' );
function exclude_pages_search_when_logged_in($query) {
    if ( $query->is_search && is_user_logged_in() )
        $query->set( 'post__not_in', array( 1, 2, 3, 4, 5 ) ); 

    return $query;
}

Exclude All Pages From Search Results

add_action('pre_get_posts','exclude_all_pages_search');
function exclude_all_pages_search($query) {
    if (
        ! is_admin()
        && $query->is_main_query()
        && $query->is_search
        && is_user_logged_in()
    )
        $query->set( 'post_type', 'post' );
}

Source http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_Pages_from_Search_Results

  • You might need the $query->is_main_query() check when excluding a specific page too. – Zlatev Oct 4 '15 at 13:27
  • i also wanted more than only posts. $query->set('post_type', array( 'post', 'OTHER_POSTTYPE' ) ); – a deer Nov 9 '15 at 12:37
  • Can someone please comment the second function so I can see what each part does. Thanks :) – Pete Apr 18 '16 at 13:12
-2

You can use this code on your theme functions.php. Note that I have not tested this.

add_filter( 'pre_get_posts', 'SearchFilter' );
function SearchFilter( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post__not_in', array( 2, 5, 12, 14, 20 ) );
    }

    return $query;
}

I get the idea from WPBeginner.

Terms of use while this was written: "(...) You are welcome to reference our snippets and hacks on your own blogs/sites as long as you give us full credit from that article.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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