Get the top level category from any category in Wordpress


/ Published in: PHP
Save to your folder(s)

Just insert any category id into the argument and it will return the top level category object.

e.g: print_r( get_top_level_category('INSERT CATEGORY ID HERE') );


Copy this code and paste it in your HTML
  1. if ( ! function_exists( 'get_top_level_category' )) {
  2. function get_top_level_category($id){
  3. $category = get_category($id);
  4. $parent_category = NULL;
  5. if($category->category_parent != 0){
  6. $parent_category = get_top_level_category($category->category_parent );
  7. } else {
  8. $parent_category = get_category($category->cat_ID);
  9. }
  10. return $parent_category;
  11. }
  12. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.