GET TOP PARENT CATEGORY (WORDPRESS),

There are many times when you need to show or get the top most (root) parent category in WordPress – regardless of how many subcategories you might be deep. I have used this logic for page navigation (highlight the top parent tab) – as well as within some custom loops/sidebar code.

They way to do this:

 

 

 

<?php

function get_cat_hierchy($parent,$args){

	$cats = get_categories($args);
	$ret = new stdClass;

	foreach($cats as $cat){
		if($cat->parent==$parent){
			$id = $cat->cat_ID;

			$ret->$id = $cat;
			$ret->$id->children = get_cat_hierchy($id,$args);
		}
	}

	return $ret;
}
$args = array(
		'type'                     => 'post',
		'child_of'                 => 0,
		'hide_empty'               => false,
		'hierarchical'             => true,
		'exclude'                  => '1'
	);
$retarray=get_cat_hierchy(0,$args);
print_r($retarray);
echo "<p><p><p><p>";
/?>

By admin-powenko

Dr. Powen Ko is a teacher and CEO on LoopTek LLC, and like to teaching. if you need to class, please let PowenKo know, he will love to service and sharing. LoopTek web site is www.looptek.com

Leave a Reply