WordPress中,有时候由于某种原因,需要将某些文章分类在分类目录小工具中隐藏,或者在首页或者分类页面中隐藏,我从网上找到了方法,转载学习下。

以下文章转载自:https://ranjuan.cn/wordpress-hide-category/


前提必须找到你需要隐藏的分类目录的id,”文章–分类目录“把鼠标移动到你要隐藏的分类目录的名字上,会在浏览器左下角显示一个网页地址,其中tag_ID=20 就是id数字(我这里是20)。

一、最新文章小工具不显示指定分类的最新文章

在wordpress小工具栏的最新文章列表中隐藏指定分类的文章。修改文件地址:wp-includes/widgets/class-wp-widget-recent-posts.php;找到如下内容区域,增加‘cat’=>-20,表示过滤分类id=20的分类。

1
2
3
4
5
6
7
8
9
10
11
12
13
$r = new WP_Query(
apply_filters(
'widget_posts_args',
array(
'posts_per_page' => $number,
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'cat' => -20
),
$instance
)
);

二、分类目录小工具不显示指定分类目录

修改文件wp-includes/widgets/class-wp-widget-categories.php;找到如下地方,增加$cat_args[‘exclude’] = ’20’; 注意这里你要隐藏的分类目录id两边必须加上单引号!如果有多个分类要隐藏用逗号隔开(如: $cat_args[‘exclude’] = ‘20,8’ )。

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$cat_args['title_li'] = '';
$cat_args['exclude'] = '20';
/**
* Filters the arguments for the Categories widget.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @param array $cat_args An array of Categories widget options.
* @param array $instance Array of settings for the current widget.
*/
wp_list_categories( apply_filters( 'widget_categories_args', $cat_args, $instance ) )

三、在主页最新文章中隐藏指定分类的文章

网上有很多教程,我这里只写最容易实现的一个。修改你主题文件夹下的index.php文件,因为每个人使用的主题不尽相同,找到while ( have_posts() ) : the_post();这句话,然后在下面加入一行代码“if (is_home() && in_category(’20’) ) continue;” 它的意思就是,如果当前是首页面且分类id=20那么就跳过文章显示。 这样做有个弊端就是,假如你每页显示5篇文章,而你最近连续发了2篇需要隐藏的类目的文章,那么你的首页可能一篇文章页没有!

1
2
3
4
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
if (is_home() && in_category('20') ) continue;//不显示 id=20分类的文章(跳过)

四、其他wordpress函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?=the_time(get_option('date_format'))?> loop循环中获取文章更新时间
文章内获取分类
<?php $the_post_category = get_the_category(get_the_ID()); echo $the_post_category[0]->cat_name; ?>
<?=the_author_nickname()?> 作者昵称
<?=get_the_excerpt()?> 文章摘要
<?=the_time(get_option('date_format'))?>发表时间
<?php the_permalink(); ?>文章地址
<?php the_title();?>文章标题
max(1, get_query_var('paged')); //当前第几页
get_template_part( 'content',''); //文章内容
<?php get_footer(); ?> 页面底部区域
<?php get_header(); ?> 顶部导航栏

<?php
//文章查询分类id=20,每页5篇文章,定位到第二页,标签是wordpress
query_posts('cat=2&posts_per_page=5&paged=2&tag=wordpress);
while(have_posts()): the_post();
echo '<a href="'.the_permalink().'" target="_blank">'.the_title().'</a>';
endwhile;
wp_reset_query();

?>

本站由 @澄哥 使用 Stellar 主题创建。


本页点击量本站点击量次。
您是本站的第个小伙伴
蜀ICP备19037348号-2川公网安备51160202511796号
本站已稳定运行