Skip to content

Instantly share code, notes, and snippets.

@crondeau
Created April 21, 2014 18:14
Show Gist options
  • Save crondeau/11151240 to your computer and use it in GitHub Desktop.
Save crondeau/11151240 to your computer and use it in GitHub Desktop.
Pull the list of categories associated with a post and display the first one only.
<?php
/* Useful code snippet if you want to display the category title on top
* of a featured image on a list of post.
* If a post is in more than one category, this snippet
* selects the first one. If no cateogry is set, the default category appears.
*/
$post_categories = wp_get_post_categories( $post->ID );
// get first category id
$first_cat = get_category($post_categories[0]);
// get category term info.
$term_link = get_term_link( $first_cat->slug, $first_cat->taxonomy );
echo "<a href='".$term_link."'>".$first_cat->name."</a>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment