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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} |
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.
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!
haha. I didn’t even consider the fact that you could have this same problem migrating from one CMS to another! Thanks for sharing that it worked for you! 🙂
odd thing though if a user makes use of the caption in the media editor , this filter strips out the caption entirely… any insight?
Hey Dallas,
The regular expression should only pull out the height & width attributes. Maybe pulling the height & width out of a caption breaks it?
I’d have someone like Codeable custom code a solution for your site.