因为主题的一些功能需要,有时候一篇文章会同时属于多个目录,所以在使用get_the_category来获取当前文章的目录时,这篇文章也会相应的输出多个目录,这本来也没什么.不过Dream在文章的顶部加上了目录导航,即显示(首页>>目录名称>>文章正文),这时候如果这篇文章刚好属于两个目录,那么当前的导航就会变成(首页>>目录1>>目录2>>文章正文).

查看到get_the_category的相应函数说明,并没有像get_the_category()函数提供exclude参数来排除某个目录不输出.所以只好把get_the_category函数重写了.但为了不影响其它地方调用该函数的使用,还是在主题的functions.php里新增一个函数比较保险.

/**
得到当前目录,可以排除某个分类
$id:default to current post ID. The post ID.
$excludeCategory:ҪĿ¼ID(category->ID)
*/
function dream_get_the_category( $id = false,$excludeId) {
global $post;

$id = (int) $id;
if ( !$id )
$id = (int) $post->ID;

$categories = get_object_term_cache( $id, ‘category’ );
if ( false === $categories ) {
$categories = wp_get_object_terms( $id, ‘category’ );
wp_cache_add($id, $categories, ‘category_relationships’);
}

if ( !empty( $categories ) )
usort( $categories, ‘_usort_terms_by_name’ );
else
$categories = array();

foreach ( (array) array_keys( $categories ) as $key ) {
_make_cat_compat( $categories[$key] );
}

if($excludeId>0)
{
for($i=0;$i<count($categories);$i++)
{

if($categories[$i]->cat_ID==$excludeId)
{
unset($categories[$i]);
reset($categories);
}
}
}
return $categories;
}

调用就简单多了,比如你想排除的目录ID为1,那么:dream_get_the_category(false,1);

做人要厚道,转载请注明文章来源: https://www.boxui.com/blog-history/809.html