WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to only show the post's child category inside the loop? (6 posts)

  1. joaoramos
    Member
    Posted 3 years ago #

    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?

  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    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; }
    } ?>
  3. joaoramos
    Member
    Posted 3 years ago #

    Thanks! That suited perfectly!

  4. caricari
    Member
    Posted 3 years ago #

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

  5. MACCoutinho
    Member
    Posted 2 years ago #

    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!

  6. caricari
    Member
    Posted 2 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic