Search code examples
wordpresswp-list-categories

How to know how many parents for a specific category?


In WordPress is there a way where we can know the number of parents categories of a current category:

-Parent 1
 -Parent 2
   - Parent 3
    - Current Category

So the function can tell me that the current category has 3 parents.


Solution

  • get_category_parents in wp-includes/category-template.php returns a string containing all parents listed as:

    Parent 1:seperator:Parent 2:seperator:Parent 3:seperator:Current Category

    So it is possible to get the number of parent categories in the following way:

    $ number_of_parents = sizeof(explode(', ', (get_category_parents($category_id, TRUE, ', ')))) - 1;

    There might be a better/more efficient way of doing this though. But if maximum performance is not that important, the above should be good enough.