在WordPress博客首页排除某些分类

对于一般的WordPress博客主题,首页都是调用最新的文章列表,如果我们希望在首页排除某些分类,该如何操作呢?最简单的方法就是通过 pre_get_posts  钩子来改变主查询。下面就是一个很好的例子,将代码添加到你主题的 functions.php 文件中:

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-4, -23' );
    }
    return $query;
}
 
add_filter( 'pre_get_posts', 'exclude_category_home' );

注意根据自己的需要,修改代码的第 3 行中的分类ID,比如你想排除分类 6 和 9,就将第 3 行改为:

        $query->set( 'cat', '-6, -9' );

就这么简单。

如果你不希望在顶部显示置顶文章,可以在第 3 行下面添加:

        $query->set( 'ignore_sticky_posts', '1' );

如果出现新文章跑到最下面,老文章在上面(也就是倒过来了),那试试添加:

        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );

扩展阅读:如何创建WordPress自定义查询

来源:

https://www.wpdaxue.com/exclude-specific-categories-from-your-blog-homepage.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32795.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?