显示当前文章分类和父分类的链接
当需要显示文章的父分类和当前分类链接时,我们可以使用这段代码:
- $categories = get_the_category();
- echo ‘<ul>’;
- echo ‘<li> Parent Category: ‘;
- foreach( $categories as $category ){
- if($category->parent != 0){
- $parent_category = get_term( $category->parent );
- echo ‘<a href=“‘ . esc_url( get_category_link($parent_category->term_id)) . ‘”>’ . esc_html($parent_category->name) . ‘ </a>’;
- break;
- }
- }
- echo ‘</li>’;
- echo ‘<li>Subcategory: ‘;
- foreach( $categories as $category ){
- if($category->parent != 0){
- echo ‘<a href=“‘ . esc_url( get_category_link($category->term_id)) . ‘”>’ . esc_html($category->name) . ‘ </a>’;
- }
- }
- echo ‘</li></ul>’;
代码原自:http://wordpress.stackexchange.com/questions/247011/access-current-post-parent-and-sub-category