Will Moore
Will Moore

Reputation: 127

How to limit the results of the_category in Wordpress?

I'm building a wordpress theme, but got stuck on a problem. It's on the blog archive page. When you go to the blog, you see a list of blog posts. And on each post preview, you see the author, title, et cetera. My problem is that I'm trying to display one category for each post preview. I don't want to show people an entire list of every category a post has. I want to limit the results of the_category() to ONE.

enter image description here

Upvotes: 1

Views: 818

Answers (1)

thingEvery
thingEvery

Reputation: 3434

You could do something like this:

$category = get_the_category(); echo $category[0]->cat_name;

However, that will just return the first category name on the list. Instead, I'd suggest using a plugin to set the primary category.

For instance, with WP Category Permalink, (possibly outdated) you can get the primary category like this:

<?php
  $perma_cat = get_post_meta($post->ID , '_category_permalink', true);
  if ( $perma_cat != null && is_array($perma_cat)) {
    $cat_id = $perma_cat['category'];
    $category = get_category($cat_id);
  } else {
    $categories = get_the_category();
    $category = $categories[0];
  }
  $category_link = get_category_link($category);
  $category_name = $category->name;  
?>                                   
<a href="<?php echo $category_link ?>"><?php echo $category_name ?></a>

Upvotes: 2

Related Questions