WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Displaying category with lowest hierarchy setting on post page (3 posts)

  1. Nessdufrat
    Member
    Posted 1 year ago #

    Not sure the title says it all...
    On the post page (single.php), I'd like to display the lowest child category of the post.
    Example :
    Animals / Mammals / Cetacae / Dolphins

    If a post is in the Dolphins category, I'd like to display "dolphins" on it (like on the top of the page, or such)

    I know how to get the categories, I know how to get the top parent category, what I need now is to get the lowest child category.

    I figured I'd do it that way :

    $category = get_the_category();
    $number = count ($category);
    echo $category[$number-1]->name;

    By getting an array of all categories assigned to my post, and by counting the number of them and substracting 1 to get the last one since the first array slot is 0.

    It's working so far, but I'd like to be sure it's correct and will not output crazy results later... Like if a post is assigned to 2 subcategories :
    Animals / Mammals / Cetacae / Dolphins
    Animals / Mammals / Cetacae / Killer-whales

    Which one would it show ? Is it possible to show both ?

    Thanks !

  2. bythegram
    Member
    Posted 1 year ago #

    I believe in a situation like you mentioned, a post assigned to both Dolphins and Killer-whales; It will only show one. I'm betting which ever one was created first (ie has the lower ID).

    You could write a foreach statement to find if the category has children and if not then show it.

    This should work.

    $categories = get_the_category($post->ID);
    foreach($categories as $category) :
    	$children = get_categories( array ('parent' => $category->term_id ));
    	$has_children = count($children);
    	if ( $has_children == 0 ) {
     	echo $category->name;
    	}
    endforeach;
  3. Nessdufrat
    Member
    Posted 1 year ago #

    Oh, thanks, that works too and it's much easier. I hadn't thought to do something like that.

Topic Closed

This topic has been closed to new replies.

About this Topic