Wordpress显示子类别标题及其链接

时间:2016-10-18 13:34:26

标签: php wordpress

显示不包含父类别的子类别

我已经测试了我在网上看到的几个功能,但没有符合我的要求。这只显示带有链接的子类别标题。例如,父类别有两个子类别。我想显示这两个子类别,并为每个子类别应用链接到各自类别的链接。

我能够抓住循环中的帖子,其中包括缩略图,帖子标题,摘录等。但是我很难实现我的需要。

我在网上找到了这个解决方案的一半。

function the_category_children($slug=""){
  if($categories       = get_the_category()):
    if($slug_category   = get_category_by_slug($slug)):
      foreach($categories as $category):
        echo (cat_is_ancestor_of($slug_category, $category)) ? $category->cat_name : '';
      endforeach;
    endif;
  endif;
}

上面的函数显示了我需要的两个子类别,但不包括父类别。但是,您可以帮我解决一下如何使用此功能为每个类别添加分隔符吗?以及添加链接到各自类别名称的链接的正确方法?我有自己的方式来添加它的链接,但我认为它太丑了,我认为它由额外的不必要的代码组成。

我希望有人能帮助我实现这一目标。在此先感谢大师! :)

1 个答案:

答案 0 :(得分:0)

我已经使用我发现online的自定义函数解决了我的问题,并进行了一些修改以满足我的要求。

function the_category_children($slug=""){
  $separator = ', ';
  $output = '';
  if($categories       = get_the_category()):
    if($slug_category   = get_category_by_slug($slug)):
      foreach($categories as $category):
        if (cat_is_ancestor_of($slug_category, $category)):
          $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
        endif;
      endforeach;
      echo trim( $output, $separator );
    endif;
  endif;
}

在循环内部调用此函数the_category_children('category_name')(content.php)。 ^ _ ^

相关问题