Solve the problem of a WordPress website that a certain category of posts does not show up

为了方便,我公司网站也是用 WordPress 程序做的,毕竟作为企业,只需要有个展示平台的网站就可以了,wordpress 程序功能强大,也用惯了,所以也就不再去折腾别的程序了。

今日在维护中,想在网站多发布一些关于行业知识的文章,但是如果在首页刷出来就不免显得有些信息冗杂,作为企业站的首页,还是针对性强一点的好,所以我马上想到要将这个categorization的文章在首页不展示,而仅仅在分类中展示。让 wordpress 网站不显示某个分类文章的办法有不少,这类的教程还是蛮多的,操作也不复杂,整理了下有三种常用的办法。

方法一

用首页模板里面的 query_posts 函数:后台 – 外观 – 编辑 – 首页模板(index.php)。直接在当前主题模板的首页 index.php 中修改调出代码,比如下面代码中是让 20 和 22 分类不显示出来。

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

修改为:

<?php if ( have_posts() ) : query_posts($query_string .'&cat=-20,-22'); while ( have_posts() ) : the_post(); ?>

方法二

还是先找到这句代码:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

如果不想在首页显示某一个分类的文章,只需要在这句代码下面再加一句:

<?php if (is_home() && in_category(‘1’) ) continue; ?>

把其中的 in_category(’1′) 这里的数字改成你不想显示出来的分类的 ID 就可以了。上面两种方法操作简洁,但是有个缺点,那就是如果想要不显示分类的文章很多的话,文章下面的翻页往后翻的话就会都是空白页面。虽然影响不大,但是对于我们这些爱折腾并且都有强迫症的草根站长来说,心里还是挺不爽的,每次点到后面都是空白页,真是叔可忍婶不可忍的事情。

方法三

functions.php 修改,这个方法是比较好的,建议使用。直接在 functions.php 底部添加代码:

 //让wordpress首页不显示某一分类文章
function exclude_category_home( $query ) {
 if ( $query->is_home ) {
     $query->set( 'cat', '-20, -22' ); //你要排除的分类ID 
  }
    return $query;
}
    add_filter( 'pre_get_posts', 'exclude_category_home' );

这个方法直接不会有任何页面空缺问题,而且在最新内容中也不会出现。直接在当前主题的 functions.php 添加上面的代码,修改对应的分类排除。修改后,首页文章列表下面的页码会减少,就是讲不显示分类的文章减掉了。

912sy.com download resources are from the network, only for learning and reference use, the copyright belongs to the original author, do not use for commercial purposes, please remove yourself within 24 hours after downloading.
If the content published on this site inadvertently violates your rights and interests, please contact us and the site will be deleted within one business day.If you encounter any problems please contact customer service QQ:2385367137
912sy " Solve the problem of a WordPress website that a certain category of posts does not show up