October 18, 2017
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.