Wordpress - How do I change/modify the_post_thumbnail(); html output?

Ok, so I think I may have come to a solution. It doesn't seem as nice and easy as I'd like it to be, but then again major modifications to default Wordpress functionality sometimes requires drastic measures. :)

This is my working solution to rewriting the HTML output for post thumbnails throughout my site to work with the Retinise.js plugin. Of course this code may be adapted for other post thumbnail HTML manipulations.

In my functions.php file, I created this function:

<?php
function modify_post_thumbnail_html($html, $post_id, $post_thumbnail_id, $size, $attr) {
    $id = get_post_thumbnail_id(); // gets the id of the current post_thumbnail (in the loop)
    $src = wp_get_attachment_image_src($id, $size); // gets the image url specific to the passed in size (aka. custom image size)
    $alt = get_the_title($id); // gets the post thumbnail title
    $class = $attr['class']; // gets classes passed to the post thumbnail, defined here for easier function access

    // Check to see if a 'retina' class exists in the array when calling "the_post_thumbnail()", if so output different <img/> html
    if (strpos($class, 'retina') !== false) {
        $html = '<img src="" alt="" data-src="' . $src[0] . '" data-alt="' . $alt . '" class="' . $class . '" />';
    } else {
        $html = '<img src="' . $src[0] . '" alt="' . $alt . '" class="' . $class . '" />';
    }

    return $html;
}
add_filter('post_thumbnail_html', 'modify_post_thumbnail_html', 99, 5);
?>

Then, whenever I call the_post_thumbnail(); in a WP loop, I use this code:

<?php the_post_thumbnail('custom-thumbnail-size', array('class' => 'retina additional-class')); ?>

This code should work (obviously with minor modifications) if you're operating outside of a WP loop. Hope this will save someone else some time and frustration! Maybe when I get around to it, I'll post a complete start to finish Q & A on how I baked in retina support to my theme. No plugins used!

Here's a few links to point someone in the right direction if interested!

  • Adding additional image sizes to WP
  • Retinise.js
  • Create additional retina-sized images

hackish solution:

since wordpress add a lot of classes by default to the <img>, if you don't change that behaviour by force, you can always 'inject' something via str_replace before the string class=. In code:

$image = get_the_post_thumbnail( $post->ID, 'medium', array( 'class' => 'myclass' ) );
$moreattrs = 'data-fullimg= "full.jpg"';

$image = str_replace('class=', $moreattrs.' class=', $image );

It's pretty safe to assume that if something starts with "class=", that's what you want. Of course, it could be messed up by weird filenames containing that class=, but especially with wordpress, that's highly unlikely.

you could also search for <img and replace that; thinking about it, I guess that should be a bit safer.