带排除项的 the_category

Avatar of Chris Coyier
Chris Coyier

WordPress 函数 the_category 没有提供 exclude 参数。这个可以

function exclude_post_categories($excl='', $spacer=' ') {
  $categories = get_the_category(get_the_ID());
  if (!empty($categories)) {
    $exclude = $excl;
    $exclude = explode(",", $exclude);
    $thecount = count(get_the_category()) - count($exclude);
    foreach ($categories as $cat) {
      $html = '';
      if (!in_array($cat->cat_ID, $exclude)) {
        $html .= '<a href="' . get_category_link($cat->cat_ID) . '" ';
        $html .= 'title="' . $cat->cat_name . '">' . $cat->cat_name . '</a>';
        if ($thecount > 0) {
          $html .= $spacer;
        }
        $thecount--;
        echo $html;
      }
    }
  }
}

另外,只要你拥有了它,你就可以根据需要更改输出,这很好。

用法如下

<?php exclude_post_categories("4"); ?>

这将列出所有类别,但 ID 为 4 的类别除外。