WordPress.org

Support

Support » Themes and Templates » [Resolved] How to only show the post's child category inside the loop?

[Resolved] How to only show the post's child category inside the loop?

  • Hello,

    I’m trying to use get_categories(); to print the current post’s child category, either by hiding its parent categories or by showing only the child categories associated to that post (I’m trying to use this both on single.php and category.php). Unfortunately, I’m new to this kind of functions and I can’t put it to work.

    Any suggestions, please?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Michael

    @alchymyth

    Forum Moderator

    first step might be to use get_the_category() to get the categories of the post;
    then, in a foreach loop use get_categories() with the child_of parameter for each of the categories of the post.
    then output these child category names in another foreach loop.

    basic structure:

    <?php $post_child_cat = array();
    foreach((get_the_category()) as $cats) {
        $args = array( 'child_of' => $cats->cat_ID );
    	$categories = get_categories( $args );
    	if( $categories ) foreach( $categories as $category ) {
    	echo $category->cat_name; }
    } ?>

    Thanks! That suited perfectly!

    how can i make them childs appear as links?
    thanks!!!

    I’m trying to show only the sub-categories that belong to the current post on single.php and came across this code. Unfortunately this code displays the sub-categories belonging to all posts and not just the current one. Can anyone give me some pointers on what to achieve what I’m looking for? Thanks!

    well i used a plugin called sobeks-post-in-category-plugin;
    worked fine for what i needed.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘[Resolved] How to only show the post's child category inside the loop?’ is closed to new replies.