OK so I wanted the parent category title to display in the category.php template file which led me to write the following handy function.

function nnm_get_the_term_parent(){
	global $wp_query;
	$cat = $wp_query->get_queried_object();
	if($cat->parent == 0) {
		$id = $cat->term_id;
	} else {
		$id = $cat->parent;
	$term_object = get_term($id,'category');	
	if($term_object) {
		return $term_object;
	} else {
		return false;

So above we’re getting the data about which page we’re on, checking whether it is a top level category, if so we assign it’s id to the $id variable otherwise we assign the parent id. Then we get the term from the ‘category’ taxonomy, you can change this to ‘post_tag’ or any custom taxonomy you have registered. Finally we do a quick check it has worked and then fire the object back on success.

The initial function above would go in your functions.php file, and because I’ve queried the ‘category’ taxonomy I need to include the below code in my category.php template, if you went for ‘post_tag’ you would add it to tag.php.

<?php $parent = nnm_get_the_term_parent(); ?>
<?php // print_r($parent); ?>
<h3 class="parent-category"><?= $parent->name; ?></h3>

That’s pretty much all there is to it, uncomment the 2nd line to output the term object to screen.

Leave a Reply

Privacy & more..

Cookie Consent Policy