码迷,mamicode.com
首页 > 其他好文 > 详细

强大的pre_get_posts

时间:2017-12-09 00:00:21      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:cat   dmi   str   ted   rod   res   lte   ges   除了   

pre_get_posts是一个强大的文章过滤器

   参考1:  

function return_only_selected_category() {
    if ( isset($_REQUEST[‘s‘]) && isset($_REQUEST[‘cat‘]) ){ //若为搜索页面,且有cat值传入
        global $wp_query;
        $desired_cat = $_REQUEST[‘cat‘]; //要搜索的分类
        $excluded = get_categories("hide_empty=false&exclude={$desired_cat}"); //要排除的分类
        $wp_query->query_vars[‘cat‘] = "-{$excluded}"; //除了要搜索的,其它都排除
        $wp_query->query_vars[‘post_type‘] ="type_product";
        //还可添加其它条件,比如要搜索的文章类型$wp_query->query_vars[‘post_type‘] ="product";
    }
}
add_filter(‘pre_get_posts‘, ‘return_only_selected_category‘);

参考2:

//文章显示过滤
function hwl_home_pagesize( $query ) {
    $num_per_page = get_field(‘cate_num‘ , ‘options‘);
    if(empty($num_per_page)){
        $num_per_page = 12;
    }
if ( is_archive() ) {
    $query->set( ‘posts_per_page‘,  $num_per_page);
    return;
}
}
add_action( ‘pre_get_posts‘, ‘hwl_home_pagesize‘, $num_per_page);

参考3:

// Exclude Pages from Search Results
function excludePages($query) {
    if ($query->is_search) {
        $query->set(‘post_type‘, array(‘post‘, ‘custom-post-type‘));
    }
        return $query;
}
if (!is_admin())
add_filter(‘pre_get_posts‘,‘excludePages‘);

 

强大的pre_get_posts

标签:cat   dmi   str   ted   rod   res   lte   ges   除了   

原文地址:http://www.cnblogs.com/lc-hj/p/8007434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!