Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to echo the category nicename to reference a category image stored in my images folder in another folder called categories.

I am using this code:

$category = get_the_category();
echo '<img src="'.get_bloginfo('template_directory').'/images/categories/'.$category->category_nicename.'.png">';

But all it returns is this:

<img src="http://www.fightfansradio.com/wp-content/themes/FFR2/images/categories/.png">

What I want is:

<img src="http://www.fightfansradio.com/wp-content/themes/FFR2/images/categories/categorynicename.png">

I haven't been able to figure out what is wrong with my code. Can I get some help please? Thanks!

share|improve this question

3 Answers 3

*get_the_category();* is designed to return multiple categories. You have to provide index for deciding which categories' nicename you want to echo.

Something like below,

$category = get_the_category();
echo '<img src="'.get_bloginfo('template_directory').'/images/categories/'.$category[0]->category_nicename.'.png">';
share|improve this answer

refer to the codex entry for get_the_category:

Returns an array of objects, one object for each category assigned to the post.

Since you can assign more than one category to a post, the function returns an array of objects. You have to reference the first element of the array to get the first category nicename:

$category = get_the_category();
echo $category[0]->category_nicename;
share|improve this answer

This get_the_category() function gets all the categories.

You should use this:

// Execute only if on category page
if (is_category()) {
  //get category ID from current page URL
  $cat_id = get_query_var('cat');
  //get category object with your current category ID
  $category = get_category ($cat_id);
  // echo category nicename from that category object
  echo '<img src="'.get_bloginfo('template_directory').'/images/categories/'.$category->category_nicename.'.png">';
 }

Cheers.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.