This tutorial will teach you how to display a single WordPress post category in your theme even if the article has been posted in a sub category. I created this technique for use in several WordPress themes I have developed where I only wanted to display the actual category that the article was posted in even when posted to sub categories. It’s a nice technique for themes with limited space or users that don’t want to display all categories that a post has been placed in.
Step 1: Creating A Retrieve Actual Category Function
Firstly you will want to open your current themes functions.php file then copy the code block below and paste it into your functions.php file at the bottom, close and save your functions.php file.
//----------------------- [ Article Category Function ] ----------------------// // This function returns the category that the article is actually posted in even if in sub-category function article_category() { $category = get_the_category(); if ($category) { echo '<a title="' . sprintf( __( 'View all posts in %s', 'wpshock' ), $category[0]->name ) . '" href="' . get_category_link( $category[0]->term_id ) . '">' . $category[0]->name.'</a> '; } }
Step 2: Using The Function Within Your WordPress Theme
Copy and paste the code below into your WordPress themes post loop function. You can search for the_category() function within your themes post loop and replace it with the code below in an existing WordPress theme.
<?php article_category(); ?>
If you have any improvements or questions about this code snippet please feel free to leave a comment.
Leave a Reply
You must be logged in to post a comment.