5

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

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

3 Answers 3

18

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

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

Add the following code to your theme’s functions.php file

it's perfectly working on my client's site.

//Exclude all except post from WordPress Search

if (!is_admin()) {
    function wse_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'post');
        }
        return $query;
    }
    add_filter('pre_get_posts','wse_search_filter');
}
1
  • 1
    How is this different / better than the posted & accepted answer?
    – kero
    Commented Dec 31, 2019 at 12:35
-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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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