0

So, let's say I have this structure of categories

  • I. Super Cat A
    • i. mini cat a
    • ii. mini cat b
    • iii. mini cat c
  • I. Super Cat B
    • i. mini cat a
    • ii. mini cat b
    • iii. mini cat c

This code:

<?php if (get_categories('child_of='.$cat.'&hide_empty=0')) { ?>
        <div class="category-wrapper">
          <ul class="child-categories">
                    <?php wp_list_categories('show_count=0&child_of='.$cat.'&hide_empty=0&title_li='); ?>
          </ul>
        </div>
<?php   } ?>

enables if I am in Super Cat A it would list all mini cat a-c,

what I want to add, is if I go to mini cat a or mini cat b or mini cat c, it would list other subcategories of its parent category, say:

current location: mini cat b

will list: mini cat a & mini cat c

Anyone?

Thanks in advance and more power.

0

1 Answer 1

2

Assuming you have only two levels of categories, you could first retrieve the parent category and then list the child categories. Furthermore, calling get_children and wp_list_categories uses more resources than necessary, using only wp_list_categories would suffice. I've explained my answer in the following snippet that should behave exactly as you need it to!

$category_id = get_query_var( 'cat' ); // Get current catgory ID
$category = get_term( $category_id, 'category' ); // Fetch category term object

// Now, we check if the category has a parent
// If it has, we use that ID
// If it doesn't have a parent, it is a parent category itself and we use its own ID
$parent = $category->parent ? $category->parent : $category_id;

$args = array(
    'show_count' => false,
    'hide_empty' => false,
    'title_li' => '',
    'show_option_none' => '',
    'echo' => false
);

// Show the children of parent category
if ( $category->parent ) {
    $args['child_of'] = $category->parent;
    $args['exclude'] = $category_id; // Don't display the current category in this list
}
else {
    $args['child_of'] = $category_id;
}

// Get the category list
$categories_list = wp_list_categories( $args );

if ( $categories_list ) {
    ?>
    <div class="category-wrapper">
        <ul class="child-categories">
            <?php echo $categories_list; ?>
        </ul>
    </div>
    <?php
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.