- Handling Navigation
- Handling Images
- Handling Widgets
- Wrapping Up
Handling Images
Images are one of the biggest sticking points for making a website truly responsive; it’s not good enough to just resize them along with the layout or container. There are a lot of tools and techniques out there to aid in better resizing, smaller file sizes, faster loading, and more. What really helps is the way WordPress processes uploaded images.
How WordPress Uploads Images
By default, when you upload an image, the WordPress media uploader creates several different sizes: thumbnail (150x150px max), medium (300x300px max), large (1024x1024px max), and full, which is the original size of the uploaded image. You can also specify different sizes using the_post_thumbnail() or get_the_post_thumbnail(), but this will only return an <img> tag with width and height specified. If you want just an image URL, you can use wp_get_attachment_image_src(), which returns an array with URL, width, height, and a Boolean; the Boolean tells you if the image is a resized version (true) or the original (false).
You can add new image sizes associated with keywords like “thumbnail,” or “medium,” for example, which will get resized. That function is add_image_size(); if you want to create a feature Destination image for the Millennium Flights CPT, you would use this code:
add_image_size('mf_destinations_featured', 650, 300, true);
In order, the parameters are: $name (which can be used in functions like the_post_thumbnail()), $width, $height, and $crop. $crop (which is false by default) tells WordPress if it should do a hard crop. A hard crop will crop to the exact dimensions specified, regardless of aspect ratio. If $crop is false, it will do a soft or proportional crop. The image’s width and height are treated as maximum dimensions.
So when you upload an image, at least three new images (or different sizes) are created. Because of this, the file size is affected; smaller images will have smaller files sizes. We can take advantage of these images by calling them using a lightweight JavaScript library called picturefill.js to show the appropriately sized images based on screen size.
Using picturefill.js
picturefill.js was created by Scott Jehl to mimic functionality for a proposed <picture> HTML element that would nicely handle responsive (and even Retina-ready) images. All of the information about it can be found at http://rwdwp.com/23.
To use it, you list several lines in this format:
<span data-src="image.jpg" data-media="(min-width: 400px)"></span>
The data-src is the image source, and the data-media is the Media Query at which the image should be used. A full block might look like this example on GitHub:
<span data-picture data-alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia"> <span data-src="small.jpg"></span> <span data-src="medium.jpg" data-media="(min-width: 400px)"></span> <span data-src="large.jpg" data-media="(min-width: 800px)"></span> <span data-src="extralarge.jpg" data-media="(min-width: 1000px)"></span> <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. --> <noscript> <img src="external/imgs/small.jpg" alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia"> </noscript> </span>
The first one is assumed to be for the smallest screens, and you can have as many entries/Media Queries as you like. The GitHub page talks about various uses before the basic example here, but this will serve us well.
As you might imagine, we can use this script along with the multiple image sizes produced by WordPress’ Media Manager to automatically generate a picturefill object that can be called in your themes:
function mf_get_featured_image($html, $aid=false){ $sizes= array('thumbnail', 'medium', 'large', 'full'); $img= '<span data-picture data-alt="'.get_the_title().'">'; $ct= 0; $aid= (!$aid) ? get_post_thumbnail_id() : $aid; foreach($sizes as $size){ $url= wp_get_attachment_image_src($aid, $size); $width= ($ct < sizeof($sizes)-1) ? ($url[1]*0.66) : ($width/0.66)+25; $img.= ' <span data-src="'. $url[0] .'"'; $img.= ($ct > 0) ? ' data-media="(min-width: '. $width .'px)"></span>' :'></span>'; $ct++; } $url= wp_get_attachment_image_src( $aid, $sizes[1]); $img.= '<noscript> <img src="'.$url[0] .'" alt="'. get_the_title().'"> </noscript> </span>'; return $img; }
There are a few things going on here. The first is that the function has an array of all the default sizes in WordPress. If you have your own sizes defined, you will have to add them here. This is so the picturefill element is accurately populated. After some setup (defining the image sizes, opening the picturefill element, initializing a counter), it moves through the $sizes, printing an image entry for each size.
For each entry, wp_get_attachment_image_src() is called to grab the URL of the image based on the image’s ID (which get_post_thumbnail_id() returns based on the post ID) and the size. wp_get_attachement_image_src() returns an array that includes the image, the width, the height, and whether or not it’s cropped. The first time through the Loop, we don’t need to specify a minimum width, since that image will be a default. That’s where the counter comes in. For the rest of the iterations, the width is calculated using a simple formula and an assumption. Let’s look at that line again:
$width= ($ct < sizeof($sizes)-1) ? ($url[1]*0.66) : ($width/0.66)+25;
What’s happening here in most cases is that we start showing the next image size up at 66% the width of the image; so if the image is 1000px, it will start being shown at 660px. However, if it is the last image in the array, the assumption is that this is the biggest image (the image at full width). There are some strange results returned in some cases with this image, so you can’t rely on the width and height returned with the full width image. We simply take the previous image’s width and add 25px to it.
The last thing this function does before returning the picturefill code is set a default image in case JavaScript is disabled. The medium image is the default.
Since this plugin requires picturefill, one more task needs to be performed, and that’s to actually add picturefill.js to the rest of the JavaScript loaded on the site. Looking at the mf_scripts() we’ve used throughout the book, you’ll notice that the line wp_enqueue_script( ‘picturefill’, TEMPPATH.’/js/picturefill.js’, array()); has already been added.
If you’d rather continue to use the_post_thumbnail() instead of a new function, or if you want this to apply to all features images/instances of the_post_thumbnail(), you can easily do that by adding this filter to your functions.php file:
add_filter( 'post_thumbnail_html', 'mf_get_featured_image');
It’s important to note that this function will not automatically run for all images on pages and blog posts; this is strictly for getting featured post images. To replace all post images would require content filters, as well as some regex magic to replace the <img> tag with the picturefill script.
There is a plugin available that will replace content images with picturefill, located at http://rwdwp.com/37. Based on my testing, it works fairly well, but you may see performance issues. That said, this might be your best bet as what I was experimenting with returned worse performance than the plugin.
Moving forward, you can also use a shortcode, along with the above function. I didn’t touch on the arguments the function accepts, but the first is $html; this is the HTML send by the post_thumbnail_html filter. The second is $aid, for attachment ID. This will allow you to call the function on any image you want, not just featured ones.
The shortcode you’re going to create is [mf_image src=’path/to/image’]. This is a shortcode that will accept a URL for an argument and print out the picturefill markup for that image. The function that does the heavy lifting is a modified version of one by wpmu.org (http://rwdwp.com/38) and is listed below, but first let’s look at the function used for the actual shortcode:
function mf_responsive_image($atts, $content=null){ extract( shortcode_atts( array( 'src' => false ), $atts ) ); if(!$src){ return ''; }else{ $aid= mf_get_attachment_id_from_src($src); $img= mf_get_featured_image('', $aid); } return $img; } add_shortcode('mf_image', 'mf_responsive_image');
The function will check to make sure a URL is passed, then grab the ID for that URL (that’s where wpmu.org’s function comes in) before passing that ID off to the mf_get_featured_image function. It will then return the HTML generated. Here is the function that grabs the attachment ID based on the URL:
function mf_get_attachment_id_from_src($url) { global $wpdb; $prefix = $wpdb->prefix; $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $url )); return $attachment[0]; }
Between the shortcode and the featured image function, you have two good methods for using picturefill and responsive images moving forward. Hopefully an efficient way to do all images will emerge in the near future. In the meantime, there is another method that can be used to make images a bit more responsive-friendly.
Overriding Set Width and Height
This is a technique that Jesse Friedman put forth in his book, Web Designer’s Guide to WordPress. jQuery would allow us to search for all <img> tags in the content and remove the set width and height attributes applied to images. This will, at the very least, ensure that the images resize properly:
$(function(){ $(".post img).removeAttr("width").removeAttribute("height"); }
You can add this function to your header (or even better, using add_action) and enqueue jQuery, and you’re all set.
CSS may also be used for the technique, though results may vary based on custom posts, images, and other CSS rules; because of that, this code may need to be tweaked:
img[class*="align"], img[class*="wp-image-"] { height: auto; } img.size-full { width: auto; }