WP笔记

如何在WordPress搜索结果中排除特定的文章或页面

有时候我们不想让某些文章或页面(Posts or Pages)出现在WordPress的搜索结果中,本文介绍如何通过WordPress的filter将某些页面或文章从搜索结果中排除,要使用他们的ID实现。

从搜索结果中排除特定文章或页面

在主题的functions.php中添加代码,假设要排除ID为40和9的文章(也可以是页面,文章和页面都有唯一的ID)

// search filter
function fb_search_filter($query) {
if ( !$query->is_admin && $query->is_search) {
	$query->set('post__not_in', array(40, 9) ); // 文章或者页面的ID
}
	return $query;
}
add_filter( 'pre_get_posts', 'fb_search_filter' );

这样就可以排除特定的文章或页面。

从搜索结果中排除所有页面

在主题的functions.php中添加如下代码,即可在搜索结果中排除所有页面

add_filter('pre_get_posts','search_filter');
function search_filter($query) {
	if ($query->is_search) {
		$query->set('post_type', 'post');
	}
	return $query;
}

从搜索结果中排除某些分类下的文章

在主题的functions.php中添加如下代码,即可在搜索结果中排除ID为1和2的分类下的所有文章

function search_filter( $query) {
if ( !$query->is_admin && $query->is_search) {
	$query->set('cat','-15,-57'); // 分类的ID,前面加负号表示排除
}
	return $query;
}
add_filter('pre_get_posts','search_filter');

参考文章

Exclude Posts and Pages in WordPress Search

WordPress 技巧:把页面从搜索结果中排除

Exclude categories from WordPress search results

3条评论

  1. 这个很实用,我已经用上了。
    顺便问一下,怎样让用户登录以后,直接回到原来的页面?而不是进入WP后台。你用什么方法实现的?

    1. wp_login_url()的参数$redirect,就是决定登陆后跳转位置的,可以更改redirect地址,方法参考这篇文章http://www.ehow.com/how_8607223_change-login-redirect-wordpress.html

      如果想在$redirect为空的情况下改变跳转地址,要用hook,参考http://www.theblog.ca/wplogin-front-page

评论已关闭。