如何在wordpress the_category() 函数生成的分类列表里移除指定分类名链接


hack the_category()身为 WordPress 中文团队不活跃团员之一,俺觉得是时候做点啥了

比如出个 hack 介绍如何从
the_category() 函数生成的分类列表里移除指定的几个分类名的链接

做过模板的小盆友都知道,一篇文章可对应多个分类,在循环

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

里,可以用

< ?php the_category( $separator, $parents ); ?>

the_category(‘*’) 输出当前文章的分类,并用菊花符 * 来分隔,比如

分类: < ?php the_category('*'); ?>

会输出

分类:wordpress*hack*category

在内部 Blog 搞皮肤的时候接到一条规则,要求有个分类叫重点的,然后又不要显示出来,仅仅用来作为 query_posts() (非常牛逼的函数,内容太多,有机会另起文章介绍强大的筛选功能) 获取文章的一个筛选条件

辣么,就需要 hack 一下 the_category() 了

很幸运 WordPress 提供了一个 ooxx 函数叫

< ?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?>

根据 Smashing Theme 的一篇文章,把如下代码丢到 functions.php 最底部的 ?> 内即可实现

function the_category_filter($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//要移除的分类ID,这里是1和5
		$exclude = array(1,5);
		$exclude2 = array();
		foreach($exclude as $c) {
			$exclude2[] = get_cat_name($c);
		}
		$cats = explode($separator,$thelist);
		$newlist = array();
		foreach($cats as $cat) {
			$catname = trim(strip_tags($cat));
			if(!in_array($catname,$exclude2))
				$newlist[] = $cat;
		}
		return implode($separator,$newlist);
	} else {
		return $thelist;
	}
}
add_filter('the_category','the_category_filter', 10, 2);

解题思路就是先获取当前文章对应的分类 ID 数组,explode() 打散,和自定义的那个ID进行对比,如果有就移除,返回过滤后再 implode() 合并后的列表给 the_category() 输出到模板对应的前台页面


《 “如何在wordpress the_category() 函数生成的分类列表里移除指定分类名链接” 》 有 38 条评论

  1. 终于找到了类似的问题,博主还在么?我需要在文章页的某个位置单独显示文章所属的多个分类中指定的一个分类,其它地方照常显示,请问该怎么破?博主这个方法貌似改了全局?盼回复,谢谢!

回复 chisdy 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注