Skip to content
Advertisement

Show all sub categories and parent on current category page in WordPress

I have this code snippet within my index.php to display all sub categories of the current category page:

<?php
if (is_category()) {$this_category = get_category($cat); }

if($this_category->category_parent)
    $this_category = wp_list_categories('orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent."&echo=0");
else
    $this_category = wp_list_categories('orderby=id&depth=1&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");

if ($this_category) { ?>
    <ul>
        <?php echo $this_category; ?>
    </ul>

However I also want to include a “Show All” link within the list which shows all the posts from the current category (and also adopts the active state when selected).

I have tried “show_option_all” in the args but this just takes me to all posts rather than all posts in the parent category. I have also tried to change the depth to 0 but this has no effect. I have been searching for a solution but couldn’t find anything relating to this exact problem.

Advertisement

Answer

Probably not the ideal solution but what I ended up doing was adding the show all item in the variable, then using str replace to check for the class and add it to the ‘all’ item if it isn’t set.

<?php
if (is_category()) {$this_category = get_category($cat); }

if($this_category->category_parent)
    $this_category = '<li class="cat-item-all"><a href="/category/'. $this_category->category_parent .'/">All</a></li>'.wp_list_categories('orderby=id&hide_empty=1&title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent."&echo=0");
else
    $this_category = '<li class="cat-item-all"><a href="#">All</a></li>'.wp_list_categories('orderby=id&hide_empty=1depth=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");

if ($this_category) { 

    if(strpos($this_category,'current-cat') == false) { 

$this_category = str_replace('cat-item-all', 'cat-item-all current-cat', $this_category); }?>
    <?php $all_posts_url = get_post_type_archive_link( 'category_parent' ); ?>
    <ul>
        <?php echo $this_category; ?>
    </ul>
<?php } ?>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement