How can I exclude pages for logged-in members from WordPress search results?
3 Answers
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' );
}
-
You might need the
$query->is_main_query()
check when excluding a specific page too. Commented Oct 4, 2015 at 13:27 -
i also wanted more than only posts.
$query->set('post_type', array( 'post', 'OTHER_POSTTYPE' ) );
Commented Nov 9, 2015 at 12:37 -
Can someone please comment the second function so I can see what each part does. Thanks :)– PeteCommented Apr 18, 2016 at 13:12
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');
}
-
1How is this different / better than the posted & accepted answer?– keroCommented Dec 31, 2019 at 12:35
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.