0

I want to display the direct category ancestor of a given post. An illustrative example:

These are the categories I have:

 Cat1
 Cat2
  Cat2.1
   Cat2.1.1
   Cat2.1.2
  Cat2.2
   Cat2.2.1
   Cat2.2.2
  Cat2.3
 Cat3
  Cat3.1
   Cat3.1.1
 Cat4

I check the whole trailing, like in:

  Cat1
  [X]Cat2
    [X]Cat2.1
        Cat2.1.1
     [X]Cat2.1.2 <-my post
       Cat2.2
        Cat2.2.1
        Cat2.2.2
       Cat2.3
  [x]Cat3<
    [x]Cat3.1
     [x]Cat3.1.1 <-my post
     Cat4

So I have 'my post' assigned to a multiple categories. Lets say I am navigating to 'my post' like this : Cat3->Cat3.1->Cat3.1.1->my post. Now, in the single post page, I want to display the name of the direct category ancestor of 'my post' (Cat3.1.1 in this case). But the question is how to do this?

1 Answer 1

0
<?php
$ancestors_array = get_ancestors($category_id, 'category');
$very_first_ancestor_id = end($ancestors_array); // Cat3
$parent_id = reset($ancestors_array); // Cat3.1

See Function Reference/get_ancestors

6
  • Yes but how to get this current category Cat3.1.1 id?
    – Justas Ju
    Feb 21, 2013 at 8:48
  • As I understand, category ancestor of a given post is not post category. So you should ask for post category. Function Reference/get the category
    – Max Yudin
    Feb 21, 2013 at 9:15
  • then I use get_the_category i get array of my post categories (Cat2,Cat2.1,Cat2.1.2,Cat3,Cat3.1,Cat3.1.1). But I as my user was navigating to 'my post' like this Cat3->Cat3.1->Cat3.1.1->my post , I need to get only current category (Cat3.1.1 in this case)
    – Justas Ju
    Feb 21, 2013 at 9:24
  • 1
    Then the only way is to check the referrer.
    – Max Yudin
    Feb 21, 2013 at 11:04
  • I can check referrer, but what if user comes from outside to 'my post' not from inner pages of my site? So we can say wordpress doesn't fully support multiple categories for one page?
    – Justas Ju
    Feb 21, 2013 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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