0

I'm trying to echo all CHILD / SUB CATEGORIES of the CURRENT CATEGORY only. This is my code, but it's displaying all child categories no matter what parent category we are on. I only need this to show the sub cats of the parent category, in my custom taxonomy.

I have tried changing this:

'parent' => 0, 

with no luck.

<?php
    $taxonomyName = "cosmetics";
    $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));   
    echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
    <div class="breaker-small">Refine Search</div>';
    foreach ($parent_terms as $pterm) {
        $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
        foreach ($terms as $term) {
            echo '<p class="filters"><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></p>';  
        }
    }
    echo '</div>
    <br />';

    ?> 

Many thanks!

1

Your code loops through all top level categories, then shows all child categories of each one, so I'm not surprised it's showing all child cats!

If you want to show the child terms of the current category (i.e. on a category archive?), use:

$current_cat_id = get_queried_object_id();
$kids = get_terms([
    'taxonomy' => get_queried_object()->taxonomy,
    'parent'   => $current_cat_id,
]);

And as a complete answer:

<?php

$terms = get_terms([
    'taxonomy' => get_queried_object()->taxonomy,
    'parent'   => get_queried_object_id(),
]);

echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>';
foreach ( $terms as $term) {
    echo '<p class="filters"><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></p>';  
}
echo '</div>
<br />';

?>
  • You're new to PHP aren't you. Here ya go. – TheDeadMedic Oct 24 '16 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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