身为 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() 输出到模板对应的前台页面
回复 ken 取消回复