• I found this code to show sub categories of [x] category and I like it, I just need to make it working as “Show sub-categories of [x] category IN CURRENT POST” because I’m going to paste this code in a widget inside posts only.

    <?php
    $subcategories = get_categories('&child_of=4&hide_empty'); // List subcategories of category '4' (even the ones with no posts in them)
    echo '<ul>';
    foreach ($subcategories as $subcategory) {
      echo sprintf('<li><a href="%s">%s</a></li>', get_category_link($subcategory->term_id), apply_filters('get_term', $subcategory->name));
    }
    echo '</ul>';
    ?>

    What is the code that will apply this code to the post the visitor is reading?

    Appreciate your help in advance.

    Thank you

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Sorry for the late reply, I’ve been away.

    Use get_the_category() inside the loop used by the widget. You will get an array of category objects. You then run a slightly modified version of your current code for each category. The ‘child_of’ argument just needs to be set to the ID of the current category.

    The resulting code could output duplicate categories if both a parent and child category are assigned to the post and that category has grandchildren. If that’s a problem, accumulate the categories first into an array, then remove duplicates before finally outputting the category links.

Viewing 1 replies (of 1 total)
  • The topic ‘child-of [x] category in CURRENT post’ is closed to new replies.