0

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!

1

*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">';
0

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;
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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