WordPress-Plugin-Development插件开发

wordpress 搜索结果中屏蔽部分Post或Page方法

1. 背景

因为很特别的原因,有时候,我们要记录一些东西,但是不想被用户通过前台搜索到,比如 你在一个 英文博客里面,写了中文的一些内容,给中国人看。

这个时候,如果老外 通过 搜索列表,搜出来了中文,那体验肯定不好。

所以 我们就需要 屏蔽掉 wordpress 的部分文章或Page.

2. wordpress 屏蔽Page的方法

  • 通过下面代码,即可实现:
// filter the page to be search in wordpress search index
function search_filter_page($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}

add_filter('pre_get_posts','search_filter_page');

3. wordpress 屏蔽掉特定ID的Post或Page

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

4. wordpress 屏蔽部分类目的Post

function Bing_search_filter_category( $query) {
if ( !$query->is_admin && $query->is_search) {
$query->set('cat','-1,-2'); //分类的ID,前面加负号表示排除;如果直接写ID,则表示只在该ID中搜索
}
return $query;
}
add_filter('pre_get_posts','Bing_search_filter_category');

这就是wordpress的强大之处,灵活得简直不像话了!

5. 附

阿里云创建子帐号地址:https://ram.console.aliyun.com/users

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注