Making Images Responsive in WordPress

I've been creating responsive WordPress themes pretty much since Ethan Marcotte wrote his Responsive Web Design article on A List Apart and I've been tinkering around with various ways to make images responsive in WordPress. I want to share my current method to accomplish it.

Here's My Solution


//http://speakinginbytes.com/2012/11/responsive-images-in-wordpress/
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'the_content', 'remove_thumbnail_dimensions', 10 );
function remove_thumbnail_dimensions( $html ) {
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
return $html;
}

view raw

functions.php

hosted with ❤ by GitHub

How This Script Works

  • This script basically takes the content and adds a filter that strips out all of the height & width attributes before printing the content to the screen
  • In addition to applying this to the content I also apply this script to the post thumbnail so your Featured Image for each blog post is also responsive

My Rationale

Separation between content and presentation – This is a biggie you hear all the time in web development. Some solutions add a filter to the image_send_to_editor filter in the admin area but by doing so we are actually permanently modifying the content of the site. We want the ability to switch back back to a static theme should we ever choose to do so – this is why we need to put the filter after the content comes out of the database.

Backwards Compatibility – This is another big issue in web. If I'm running a website and I don't want to update all of my previous posts & pages then we need to implement a solution that affects content already in the database. Putting the filter after the content comes out of this database solves this.

4 thoughts on “Making Images Responsive in WordPress

  1. had a whole lotta posts with height and width attrs on the img tags coming into a wordpress database from joomla. this worked a charm, thanks!

  2. odd thing though if a user makes use of the caption in the media editor , this filter strips out the caption entirely… any insight?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.