Making images responsive in your wordpress theme

It’s fashionable nowadays to have responsive websites, consequently you also end up with responsive wordpress themes, like the one used in this blog.

In bootstrap 3 images can be made responsive-friendly via the addition of the img-responsive class.

If you want to make your images responsive in wordpress, add a functions.php file in the wp-contents/themes/your_theme directory as explained here, with this content:

<?php
function my_image_class_filter($classes) {
 return $classes . ' img-responsive';
}
add_filter('get_image_tag_class', 'my_image_class_filter');
?>

(if you already have a functions.php file, add this code to the end – but beware the PHP sadness !)

The added code is using the wordpress add_filter function to hook the user-supplied my_image_class_filter function to filter the get_image_tag_class builtin function. The my_image_class_filter function appends the img-responsive class to the classes wordpress always adds to images.

For example if I add this very wide (1920px) image (courtesy http://lorempixel.com), it should be responsive:

cats-q-c-1920-200-5Hoorrah ! Indeed it’s responsive.

But of course this only applies to images added from now on, not to the images already present in the blog !

To fix old posts, we had to dig into the wordpress database tables; normally it’s the wp_posts table you have to look for, in this case (it’s a multisite wordpress install) the table is wp_2_posts. You need console access to the server, and some practice with mysql, the The MySQL Command-Line Tool. Start mysql with:

mysql -u my_user -pmy_password my_database

where you’ll replace my_user, my_password and my_database with the actual values of the DB_USER, DB_PASSWORD and DB_NAME in your wp-config.php file.

Then use this query to show the contents of a given post:

select post_content from wp_2_posts where id=873;

and this one to make images responsive selectively just for that post:

update wp_2_posts
  set post_content = replace(post_content,' wp-image-', ' img-responsive wp-image-')
  where id=873;

If you feel bold, a more radical option is to use wp-cli with something like (untested !):

wp search-replace ' wp-image-' ' img-responsive wp-image-' wp_2_posts --url=wp.libpf.com

good luck !

avatar

About paolog

homo technologicus cynicus
This entry was posted in Howtos and tagged . Bookmark the permalink.

Leave a Reply

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