Find Top-most Category in Loop

On the category archive, or the single post page, use the following loop to retrieve the name, slug or ID of the top most category to use as a header, or link.

<div id="home_posts">
    
    <?php $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3
    ); 
    
    $feed = get_posts($args);
    
    foreach($feed as $post) : setup_postdata($post); 
    	
    	$cats = get_the_category($post->ID);
	$parent = get_category($cats[0]->category_parent);
		
	if (is_wp_error($parent)){
		$cat = get_category($cats[0]);
	} else {
		$cat = $parent;
	}
    	
    	<div class="blog_post">
    	        <?php echo '<h4 class="post_category"><a href="'.get_category_link($cat).'">'.$cat->name.'</a></h4>'; ?>
                /* The rest of your content goes here */
        </div>

    <?php endforeach; wp_reset_postdata(); ?>
    
</div><!-- #home_posts -->

Sourced here.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.