I'm using post thumbnails to link to a page.

Is it possible to add a class name to the post thumbnail image.

<li><a href="<?php the_permalink(); ?>" ><?php the_post_thumbnail(); ?></a></li>

Yep - you can pass the class you want to use to the_post_thumbnail() as part of the attributes argument, for example <?php the_post_thumbnail('thumbnail', array('class' => 'your-class-name')); ?>

Ref: http://codex.wordpress.org/Function_Reference/the_post_thumbnail#Styling_Post_Thumbnails

| improve this answer | |
  • 5
    But this will remove the class attachment-$size. – fuxia Jun 6 '13 at 20:21
  • 1
    But can you add the class "attachment-$size my-class-name" – Simon Cooper Jun 7 '13 at 5:45
  • @SimonCooper I did and the class now has attachment- without the size. – Zhianc Apr 27 '15 at 10:33
  • This is generally bad and non-generic solution. Even hardcoding attachment-$size, erases all possible future class injections. – Fusion Feb 18 '19 at 11:18

You can filter those classes.

function alter_attr_wpse_102158($attr) {
  $attr['class'] .= ' new-class';
  return $attr;

Add the filter just before you call the_post_thumbnail. The filter will remove itself automatically.

It is a bit of trek to get there but the_post_thumbnail uses get_the_post_thumbnail which uses wp_get_attachment_image which applies that filter.

| improve this answer | |
  • Does the function name 'alter_attr_wpse_102158' have a particular meaning could this function be called myClass - function myClass($attr) { – Simon Cooper Jun 7 '13 at 15:17
  • The name is somewhat descriptive and the suffix references this question. Otherwise, no particular meaning. From inside a class instance-- say a plugin class-- you can use array($this,'methodname') and you can use static classes with filters by using array('ClassName','methodname') – s_ha_dum Jun 7 '13 at 15:23
  • 1
    Why are you adding a filter that removes itself? – AlxVallejo Sep 29 '13 at 12:36
  • 2
    @AlxVallejo : So that it only runs once in the particular circumstance that that you want it to run. – s_ha_dum Sep 29 '13 at 14:11

Your image tag have no class you just write this code <?php the_post_thumbnail(); ?> but your image tag have class you just write this code

<?php the_post_thumbnail('thumbnail', array(
'class' => 'class_name'

)); ?>
| improve this answer | |

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.