I have a number of top-level categories including “News” and “Sport”. They each have multiple levels of child categories as shown below.
-
News
- Australia
- NSW
- Sydney
- NSW
- Australia
-
Sports
- Cycling
- Road Cycling
- BMX
- Triathlon
- Cycling
In my loop I want to display a single category – what ever is the deepest child category of “Sport”.
I have found some code on StackOverflow that does returns the deepest child category, but not from a specific category. It returns the the deepest child category from all top-level categories. So if a post is in two categories (Sydney and Triathlon) the code shows Sydney as the deepest child category. I somehow need to specify that which top-level category I want the deepest child to come from. In this case that would be “Sport” and the deepest child cat would therefore be “Triathlon”.
The code you referenced in your question is flawed. In most cases it will work but it relies on an assumption that newer child terms are created after their parents, and as a result, have higher IDs.
To fool the code you posted, do this:
You also have the other problem of specificity. In your example, you specify that it should look inside sport, not all, but how would the code know to look specifically in sport? This sounds like you plan to hardcode the Sport category name or ID into your code, which I STRONGLY advise against. Instead a post meta value or metabox UI would be better but not ideal.
Your question can be distilled to this:
This gives us 2 new questions:
The answers to those questions would implement these 2 functions:
get_term_depth( $term )
– returns the depth or number of parents a term hasis_term_ancestor( $term, $ancestor )
– is this term an ancestor of another term? Returns true or falseThese functions are not a part of WordPress core, and will need to be written.
But if using these 2 functions we could then do this:
Which you could then use like this:
You’ll note I went directly to the taxonomy term API rather than using the higher level middle men such as
get_the_category
. This way the code is just as valid for custom taxonomies. E.g. a product category.The implementation of
get_term_depth
and the implementation ofis_term_ancestor
I leave as a task to the reader, and encourage 2 new questions be asked, as they are each useful and interesting questions in their own right. It’s important to break down a task into smaller parts, repeating the process until each part is solvable or bite sized. Both functions would require an understanding of recursion to implement.OK – I originally misunderstood your question.
I have solved a similar problem based on above mentioned ideas and I have created a gist, That can be viewed here.
1st I created a function that gets a term’s depth
then I used it with in following code
I hope it will help.
So what you are missing is, to specify a category. Why dont you do it? It’s simple