Breadcrumbs Based on Deepest Term

Breadcrumbs Based on Deepest Term

  • Share on Pinterest

While working on the RealHomes theme, I came across this requirement to build a breadcrumb for property custom post type that should be based on the deepest term of a chosen custom taxonomy. So, I am going to share the solution I came up with. This solution can be further refactored and improved based on your needs.

First, we need a function to calculate the hierarchical depth of a given term related to a given taxonomy. So, I came up with a function displayed below that uses the get_ancestors function to return an integer value that represents a term’s hierarchical depth.

The function given below generates an array in which each array item represents an item in the resulted breadcrumb. This function starts with adding Home in the array. Then it finds out the deepest term for a given taxonomy. And after that, it works on that deepest term’s ancestors to build a full array of breadcrumb items.

The code given below represents the usage of breadcrumbs items generated by the function above. I am getting the chosen taxonomy from theme options but you can hard code it if you need to.

I hope these code snippets will help you in your project. Thanks

This site uses Akismet to reduce spam. Learn how your comment data is processed.