1
votes

I can see there is already a lot of information on this, but I can't seem to find anything up to date and just wondered if someone can help me.

I have different parent categories and sub-categories, for example:

Web Hosting

  • Reviews
  • Coupons

Domain Registrars

  • Top registrars
  • Discount Codes

I am using the following code in the category.php page and it displays the sub-categories in each category fine:

<?php 
if ( is_category() ) {
$this_category = get_category($cat);
if($this_category->category_parent):
else:
$this_category = wp_list_categories('orderby=id&depth=5&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
echo '<ul>'. $this_category . '</ul>';
endif;
} 
?>

But when I click on a sub-category link it displays all the posts in that sub-category fine, but then there are obviously no links back to the parent directory etc.

Is there anyway of doing this? Does anyone have some code for me that doesn't have any bugs? Thanks a lot.

1

1 Answers

1
votes

You can modify your code to something like this:

<?php

if ( is_category() ) :
    $category = get_category( $cat );
    if ( $category->category_parent ) : // if category has parent
        $category_parent_id = $category->category_parent;
        $category_parent_link = get_category_link( $category_parent_id );
        echo '<a href="' . $category_parent_link . '">' . get_category( $category_parent_id )->name . '</a>';
    else : // else category has children
        $children = wp_list_categories( array(
            'child_of' => $category->cat_ID,
            'depth'   => 5,
            'echo'     => 0,
            'orderby' => 'id',
            'title_li' => '',
        ) );
        echo '<ul>' . $children . '</ul>';
    endif;
endif;

This is one way of doing it. There are other ways too. I can suggest these functions for that: