1
0

过滤wordpress搜索页面和文章的几种方法

2011/05/11 · 1条评论 

在维护你的wordpress博客网站时,你有时希望把一些页面和文章”私有化”,不希望被用户搜索到,这里我收集了一些可行的办法分享给大家,这些方法都在3.1.2版本测试过。
1,如果你想过滤所有页面,你可以在function.php 加入以下这个函数:

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

函数的功能主要是设置搜索的范围是文章类。

2. 上面这个方法可以过滤所有的页面,但是有时如果你只想过滤一两个页面或文章,那要怎么办呢?很简单,两种办法:
1). 同样可以在function.php页面加入以下这个函数:

function mySearchFilter($query) {
      if ($query->is_search) {
             $query->set(‘post_not_in’, array(8,15));
      }
     return $query;
}
add_filter(‘pre_get_posts’,'mySearchFilter’);

其中 8和15 为文章或页面的id. 你可以添加任何数量的id.

2). 如果以上两种都不能满足你的需求,也许可以尝试这个方法: 到search.php页面下找到这行代码:

if (have_posts()) : while (have_posts()) : the_post(); 

然后在 the_post(); 后面加入以下这个条件:

 if($post->ID==8 || $post->ID ==15) continue;

最后的代码如下:

if (have_posts()) : while (have_posts()) : the_post();
if($post->ID==8 || $post->ID ==15) continue;

相比之下2.1的方法更方便,但是2.2的方法也很灵活。

您可能也喜欢

1条评论

  1. 倡萌 说道:

    呵呵,学习一下技巧,方便以后修改主题

与大家分享点什么吧: