Getting WordPress to play nice with responsive images

Getting WordPress to play nice with responsive images

  • Knowledge needed: Basic PHP and CSS
  • Requires: WordPress install, text editor of choice
  • Project time: 10 minutes

Frontend designer David Smith responds to Jesse Friedman's article on responsive design with WordPress and presents an alternative way to deal with images

If you subscribe to the print version of .net magazine (if not, why not!?), you will have seen that this month’s issue features an excellent article on “Responsive Design with WordPress”.

In the article, author Jesse Friedman outlines a load of really useful techniques for making the most of, and overcoming, inherent WordPress functionality in order to produce a truly effective responsive website. If you’re thinking of producing a responsive site with WordPress you should definitely pick up a copy of his article. It’s a must-read.

Having recently rebuilt my personal blog on WordPress using a responsive, mobile-first approach I was familiar with some of the techniques covered in the article. However, the one item that really stood out for me was Jesse’s approach to enabling fluid images via jQuery.

The problem with WordPress and “fluid images”

As I'm sure you’re all aware 'fluid images'  – which make use of max-width: 100% – require that images have no fixed width or height in order that they can scale to the size of their container. Unfortunately, WordPress automatically calculates the dimensions of images generated from the Media library and adds the corresponding width and height attributes to any <img> tags.

This is great for page rendering speed but it throws a massive spanner in the works when it comes to creating responsive layouts as image dimensions are no longer constrained to the size of their container.

That’s a problem.

The non-jQuery solution

In his article Jesse’ suggests using jQuery to remove the width and height attributes from all <img> tags on the page once it has loaded. This certainly works but when building my site I didn’t like the idea of relying on JavaScript to achieve this, especially if there were a lot of images on the page in question.

This is where WordPress filters came to the rescue.

The WordPress codex defines a filter as:

“...hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.”

As it turns out this is exactly what we need. By setting up a filter to run on all images as the final action before they are rendered on the page, we can use PHP to remove the width and height attributes thereby circumventing the need for (potentially) expensive DOM manipulation via JavaScript.

The code

  1. /**
  2.  * RESPONSIVE IMAGE FUNCTIONS
  3.  */
  4.  
  5. add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
  6. add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );
  7.  
  8. function remove_thumbnail_dimensions( $html ) {
  9.         $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
  10.         return $html;
  11. }

In the code above we’re adding two filters using the add_filter function. The first argument is the filter we want to hook into and the second specifies the function we want to run when the filter is called.

In our code we hook into two obscure functions:

  1. post_thumbnail_html – images retrieved with the post_thumbnail()
  2.  image_send_to_editor – images added to the editor

We then using a regular expression to remove both the width and height attributes from the image tags. Now when our images are sent to the browser they can be fully 'fluid' just like Mr Marcotte told us they should.

A confession

I have to confess having had the idea of using add_filter to remove attributes I could not for the life of me locate the correct WordPress filters to hook into.

After a lot of searching I finally came across this extremely helpful post on Wordpress Stack Exchange by Nathaniel Taintor which provided the information about the two filters I needed.

Caveats

As far as I know the only major draw-back to this approach is that it doesn’t remove the width and height attributes from all images on your site. I found this to be an issue, specifcally with the Gravatar images WordPress uses in comments.

If anyone has a solution to this issue please do leave a comment so we can all benefit.

I hope this has been useful and demonstrated an alternative to relying on JavaScript to implement “fluid images” on WordPress websites.

14 comments

Comment: 2

Thanks for the tutorial and info.

It seems to be a great idea in practice but isn't it adding extra php requests to the website server which are then slowing down websites? Adding this to the fact you can't alter gravatars and some other images, isn't the jQuery option most suitable?

Comment: 3

I can't be sure but I always thought that in CSS you could set the width/max-width to 100% and then set the height to auto on images. This way it will override what was set as the width/height in HTML and allow them to flow responsively.

I believe this is what the default theme for WordPress to make its images responsive.

Comment: 4

Nice!
But this way isn't the same image served but just at smaller dimensions?
I think it's better to deliver smaller size thumbnails for devices with known bandwidth limitation.

Great job anyway!

Comment: 5

@burning Glad you found this useful as an alternative to the plugin.

@stoffb I guess it's a trade off. I'm not an expert but I can't imagine the technique in the post is a greatly server intensive task as we're not manipulating images, we're just removing attributes. My personal preference is for this to be dealt with on the backend rather than having to wait for jQuery to parse the DOM on page load. Love to hear any research you have on this.

@rkrug That's true but then I believe you'd then be forcing the img to be 100% wide (width: 100%). This would might then cause distortion of the img due to stretching if the width of the container exceeded that of the original image dimensions. Does that make sense? Please correct me if I'm wrong. I also think it's better to just remove them rather than have to overide them...

@GeorgeDina I agree. The post didn't really intend to cover this topic but perhaps I could have mentioned it. Ideally you should start with a small image and enhance to larger images for more able devices. Nonetheless the technique above is still valid if you want your images to be responsive.

Comment: 7

I'm sorry, but those additional steps are just not needed. Using max-width: 100% along with height: auto on all img elements is enough to overwrite the width/height attributes. And no, the images won't get stretched to 100% if they're smaller in width than their container (width: 100% would do that)

Comment: 8

@mpoelstra That's useful - thanks.

@kremalicious No need to be sorry :) That's correct. However, the original comment said "...you could set the width/max-width to 100%...". Having width 100% would stretch the image. However, as you correctly point out setting width and height to "auto" would solve the issue. Thanks for pointing out this alternative solution - really appreciate the feedback. Looks like there are a few options to resolving this issue!

Comment: 9

This is a great addition to my article especially since you are tapping into the WordPress API. There are a lot of solutions out there and I think the jQuery one I suggested is very simple but also extremely broad. There are many times where I want to an image to be 50% width and have text float alongside it. The best solution would be for us to find a way to choose a percentage width for images when we upload them to WordPress. That way UserAdmins would be able to modify the image size themselves.

Comment: 10

@getdave You're welcome and good to see many solutions for the same problem. I do like your approach here cause it makes the code cleaner.

But please be aware of another problem with this: without width/height on the img the space required for the image isn't reserved on page load. This will make the layout of the page change during initial loading, cause the img elements are collapsed first and won't get their full height on the page before the browser has loaded the complete image file

Comment: 11

@professor HTML5 doesn't allow anything else than px-based units on img width/height elements so you would need to find a css-based solution

Comment: 12

@kremalicious thanks, but I was referring to having a way to select percentages in the WordPress admin upon image upload

Comment: 13

Hi, by using the function above the images I get using wp_get_attachment_image come using width and height. For betting rid of w/h I´m using this in the foreach preg_replace('#(width|height)="\d+"#','',$attachmentimage) being the $attachmentimage wp_get_attachment_image.
Any suggestion I can i get the same using the filter?

Comment: 14

Such a simple solution and can save a lot of time while making own layouts. But on the other side, people who are seeking an aid to the mentioned issue have already lost a lot of time to figure out how to solve it or (probably mostly) find a ready solution in the web.
June issue on sale now!

The Week in Web Design

Sign up to our 'Week in Web Design' newsletter!

Hosting Directory
.net digital edition
Treat yourself to our geeky merchandise!
site stat collection