在WordPress 开发过程中,我们经常会遇到排除搜索结果中不想要的文章OR页面 or不显示某个分类,下面WP模板园就把代码贴出来,希望对你有所帮助。
实例一:搜索结果排除特定 ID 的文章或页面
//搜索结果排除特定 ID 的文章或页面 function wpmby_search_filter_id($query) { if ( !$query->is_admin && $query->is_search) { $query->set('post__not_in', array(13,14));//需要排除的文章、页面 ID } return $query; } add_filter('pre_get_posts','wpmby_search_filter_id');
实例二:搜索结果排除特定分类下所有文章
//搜索结果排除特定分类下所有文章 function wpmby_search_filter_category( $query) { if ( !$query->is_admin && $query->is_search) { $query->set('cat','-11,-13'); //分类的 ID,加负号表示排除;直接写ID,则表示只在该 ID 中搜索 } return $query; } add_filter('pre_get_posts','wpmby_search_filter_category');
实例三:只对指定的类型进行搜索
//另有其他方法 /** *[只对指定的类型进行搜索] *@param[type] $query [搜索的参数] */ function SearchFilter($query){ //仅搜索时 if($query->is_search){ //设定指定的文章类型,这里仅搜索文章 $query->set('post_type','post'); //指定文章和自定义类型 //$query->set('post_type', array('post','custom-post-type')); //排除指定的文章ID号 //$query-->set('post__not_in', array(10,11,20,105)); //搜索指定的类型 //$query->set('cat','8,15'); //搜索条件.... } return $query; } add_filter('pre_get_posts','SearchFilter');
使用方法:
把上面的代码复制粘贴到functions.php里面,就可以了。