Jul
26th
Mon
26th
Wordpress code: Find parent category of blog post
On MyBankTracker.com we introduced a new category structure. For reasons I won’t get into, I needed to find the parent category of the current post’s category. But, finding the parent category was surprisingly difficult using standard Wordpress functions. Anyways, this code is based on get_category_parents() which can be found in wp-includes/category-template.php. Note: this is tail recursive, so it could be rewritten to be iterative. Feel free to copy and redistribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Recursively traverse the parent child relationships of categories, returning when found the parent with no parents // $id is the child category, ignore $visited on the first call (based on get_category_parents() in category-template.php) // Used on: http://www.mybanktracker.com/bank-news/ function mbt_get_category_parent( $id, $visited = array() ) { $parent = &get_category( $id ); if ( is_wp_error( $parent ) ) return $parent; if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) { $visited[] = $parent->parent; return mbt_get_category_parent( $parent->parent, $visited ); } return $parent; } |
As expected, use this code at your own discretion. No support or liability implied by sharing this.
