Hopefully a simple question. I've added several post thumbnail sizes to functions.php using add_image_size. They are each named exactly like a post category. I would like to find a way of making each post call the specific thumbnail size assigned to it's category.

The best way I can imagine doing it is by inserting the category name into the thumbnail string like so:

<?php the_post_thumbnail( 'INSERT CATEGORY NAME HERE' ); ?>

What could I put in this php string to make it insert the category's name into this?

Thank you.

  • 2
    The problem with this, if it does work, is that you can assign multiple categories to a post. So you're either going to have to enforce a single category policy on all your posts or you will have to pull out the first key of an array. – Cedon Jun 5 '17 at 23:55
  • I didn't think of that. I suppose an array is something i'd have to factor in too. Or if possible, for it to just detect one of the 3 possible categories I was going to assign different size thumbnails too. – mastercoeurl Jun 6 '17 at 0:44
  • The thing is though, it's always going to look for the [0] key. So if you assign it category 1 and category 2, it will use 1's thumbnail always. – Cedon Jun 6 '17 at 0:53

As @belinus mentioned, you can assign multiple categories to a post, so you have to decide which one to pass to the_post_thumbnail().

One approach would be to use get_the_category(), which returns an array, then grabbing the first result from that function as your thumbnail size:

$categories    = get_the_category();
$thumbnail_cat = ! empty( $categories[0]->slug ) ? $categories[0]->slug : '';

the_post_thumbnail( $thumbnail_cat );
  • Hmm if I add this into a php tag it gives me this error: Warning: Illegal offset type in isset or empty in /srv/users/serverpilot/apps/zwp/public/wp-includes/media.php on line 747 Recoverable fatal error: Object of class WP_Term could not be converted to string in /srv/users/serverpilot/apps/zwp/public/wp-includes/media.php on line 884 – mastercoeurl Jun 6 '17 at 1:27
  • Oops, I missed that get_the_category() returns an array of WP_Term objects and not slugs. I've updated my answer to look for the term slug for the $thumbnail_cat string. – Morgan Estes Jun 6 '17 at 1:50
  • 1
    That fixed it! It's all working perfectly now. Thank you so much. You cleared up a big headache for me. – mastercoeurl Jun 6 '17 at 2:03

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.