20

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>
41

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

  • 5
    But this will remove the class attachment-$size. – fuxia Jun 6 '13 at 20:21
  • 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 at 11:18
6

You can filter those classes.

function alter_attr_wpse_102158($attr) {
  remove_filter('wp_get_attachment_image_attributes','alter_attr_wpse_102158');
  $attr['class'] .= ' new-class';
  return $attr;
}
add_filter('wp_get_attachment_image_attributes','alter_attr_wpse_102158'); 

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.

  • 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
  • 1
    @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
0

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'

)); ?>

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.