Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to show the last category level of a post

for example, I hav a post in category "Course -> resultat -> Trail"

I want to show just "trail"

Thanks if somenone can help

share|improve this question

3 Answers 3

up vote 0 down vote accepted

Try the following. I've used get_the_terms so it is readily extendible to any taxonomy.

This will return an array of terms (event if it contains just one). For instance, the post may have terms a,b,c,d,e in the relationship:

a   >   b  >   c      (parent > child)
d   >   e

In which case the following will return (as an array) the terms c and e. Whereas with the structure

a   >   b  >    c  >  d   >   e      (parent > child)

It will return an array of one term - e.

//Get all terms associated with post in taxonomy 'category'
$terms = get_the_terms(get_the_ID(),'category');

//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');

//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));

//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids,  $parents);

//Get corresponding term objects
$terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);
share|improve this answer
    
Perfect, it works !! Thanks a lot –  Hilflo Net Jun 21 '12 at 8:51

This will work if you don't assign multiple categories to the posts.

$categories = get_the_category(); 
echo 'Post categories: ' . implode(', ', $categories);

or just

echo get_the_category_list( ', ' );

Updated according the first comment.

share|improve this answer
    
Yes but I have multiple category for same popst –  Hilflo Net Jun 20 '12 at 11:17
    
Then you should write it in your question. Code updated. –  Max Yudin Jun 20 '12 at 11:40
    
The problem is that I don't want all the list, I just need the last level category –  Hilflo Net Jun 20 '12 at 12:42

this work for me

 $allCat = get_the_category();
 $lastCat = array_reverse($allCat);
 echo $lastCat[0]->name;
share|improve this answer
    
I'm not so sure that get_the_category orders them in parent-child order. I think it orders just by term ID. –  Stephen Harris Jun 20 '12 at 14:45
    
as OP said : Course > resultat > Trail –  Gembel Intelek Jun 20 '12 at 14:49
    
Yes, but I don't think that the last term in $allCat will necessarily be 'Trail'. I think the last term $allCat will be the term with the highest ID. –  Stephen Harris Jun 20 '12 at 15:00
    
I will try it thanks, but I think, I will use a meta box, this fucntionnality is just to show the name, not for link –  Hilflo Net Jun 20 '12 at 15:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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