强大的pre_get_posts

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');

 

转载于:https://www.cnblogs.com/lc-hj/p/8007434.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值