Menu Search
Jump to the content X X
SmashingConf London Avatar

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf London, dedicated to all things web performance.

Better Image Management With WordPress

With the advent of sophisticated and user-friendly content management systems like WordPress, textual content has become increasingly easier to manage. The architecture of these systems aims to deliver a well-formed code foundation; this means that if you are a good writer, then your content will be just as awesome as the structure and quality of the code that runs it.

A minimalist gallery of paintings with a beautiful wooden bench1

However, media handling is, by nature, not the greatest. In many cases, images are used merely to make the website look good, not to supplement the content. Little care is usually taken to make these elements as useful as their textual counterparts. They are often tacked on as an afterthought; the owner thinks, “If all of my posts have an image, surely I should find something quickly for this next one as well.”

Further Reading on SmashingMag:

Because the content of images cannot be parsed by search engines, making sure they are rich in meta information before publishing them is important. Here are a few ways to enrich your blog using some common sense, best practices and the power of WordPress.

Understanding And Using Images Link

To get the most out of your graphic content, you’ll need to be familiar with how they work in HTML. To put an image on a page, you would add an image tag, with the appropriate attributes, like so:

<img title="A duck" src="" alt="A mallard duck landing in the water" >

As you can see, the tag has three attributes that contain information about the image:

  • src is the URL source of the image file;
  • alt, or alternative, text is shown when an image can’t load (whether because of a loading error, text-only browser, etc.);
  • title is the title attribute, where you can add a short description of the image, which will pop up after hovering over the image for a second.

The src and alt attributes are both required; the HTML is invalid without them. However, HTML is not a strict language. Your post will still render just fine if you leave out the alt text, which is one of the negative aspect of loose languages: it doesn’t force best practices.

Why Use Alt and Title Attributes? Link

The most useful aspect of alt and title is that they allow you to add text-based information to an element on your website that would otherwise be invisible to search engines. If you sell umbrellas, Google won’t see that one particular image on your page is of the coolest umbrella it’s ever seen. You’ll have to add that information yourself.

Also, alt attribute can be a huge help to the disabled, because this is how they know what is in an image. So, use the title attribute to write something snappy about the image, and use the alt attribute to describe it. Sticking with our umbrella example, the incorrect way to do this would be:

<img title="Awesome umbrella" src="awesomeumbrella.jpg" alt="The most awesome umbrella ever" >

And the correct way would be:

<img title="Awesome umbrella" src="awesomeubrella.jpg" alt="A matte black cane umbrella with a spruce handle and a chrome tip" >

Remember, the alt attribute is descriptive not only for the visually impaired, but for Google as well. Your website might even rank better if it’s image-heavy.

While not as critical, it is probably worth optimizing the file name as well. The name o290rjf.jpg won’t get in the way showing the image, but super-sleek-umbrella.jpg is a parsable bit of text, and there is a chance that some search engines would take it into account. Also, if someone downloads the image from your website, they will be able to find it more easily in their “Downloads” folder. And user satisfaction translates into more visits.

Adding Images Properly With WordPress Link

WordPress allows you to attach media to posts very easily through the “Add media” modal window, which you can access by clicking one of the icons over the editing toolbar in a post. You can select multiple images and upload them to the post with a click. Because this is so easy, adding the meta attributes is often overlooked and regarded as a hassle.

When uploading images, make sure to fill out the form which is displayed. Add the title and alt attribute at a bare minimum, but also consider filling in the caption and description fields. If you want a short, nicely formatted caption to appear under the image (which is a good idea), type one in. We’ll look later at harnessing the description field, so writing a paragraph or so about the image might be a good idea.

Once done, all you need to do is insert the image, and the correct HTML tag will be plopped in by WordPress automatically. By taking an extra minute, you will have added a sizable bit of text to your image, making it SEO-friendly and in turn making your website that much more informative. If this is all you have time for, then you have done the most important step. But let’s look at some more advanced image-handling techniques.

Managing Image Sizes Link

If you display an image at a size of 450×300 pixels, then having an image file of roughly the same size is a good idea. If the source file is 2250×1500 pixels, the image will show up just fine, but instead of loading a 50 KB image, you would be loading a 500 KB image, while achieving the same effect.

WordPress is super-smart, though, taking care of this for you by churning out different sizes for each image you upload. See the dimensions it creates by going to the media settings in the back end. You can modify these once you have the final layout, which I would advise.

For an image-centric website, you might want to add a couple of more sizes, to make sure you never serve an image that is bigger than needed. By putting the following code in your theme’s functions.php file, you create two extra sizes:

add_image_size( 'large_thumb', 75, 75, true );
add_image_size( 'wider_image', 200, 150 );

The first line defines an image that is cropped to exactly 75×75 pixels, and the second line defines an image whose maximum dimension is 200×150, while maintaining the aspect ratio. Note the name given in the first argument of the function, because you will be referring to it when retrieving the images, which you can do like so:

wp_get_attachment_image_src( 325, 'wider_image');

The first argument is the ID of the attachment that we want to show. The second argument is the size of the image.

Rebuilding Your Thumbnails Link

If you have been blogging for a while now, you probably have a ton of images. Adding an image size now will not create new thumbnails of your existing images. If you specify an image size—for example, our wider_image format—WordPress will fetch a resolution that is close to it, but it won’t create a thumbnail especially for this size.

Using a plug-in, however, you can go back and regenerate the thumbnails to make sure that all of the images are optimized, thus minimizing server load. I can personally vouch for AJAX Thumbnail Rebuild6, which goes through all of your images and regenerates the selected sizes for you.

A featured image can capture the message of a post. Featured images have many uses: for adding flare in a magazine-style layout, underlining a point made in an article, or substituting for an article’s title (in the sidebar, for example).

Featured images have been built into WordPress since version 2.9, so you don’t need any special plug-ins. If you are using the new default WordPress theme, then featured images are already enabled. Otherwise, you might need to switch them on manually. To enable them, just open your theme’s functions.php file, paste in the code below, and voila!

add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 115, 115 )

The first line of code tells WordPress to enable featured images, while the second sets the default size for featured thumbnails. The set_post_thumbnail_size() bit works just like the add_image_size() function we looked at above. You can give it a width, a height and, optionally, a third boolean parameter (true or false) to indicate whether it should be an exact crop.

Once that’s done, go into the back end and edit a post. You should see a featured image widget in the right sidebar; click it to add an image. Or navigate to the media section of the post, view an image’s details, and click the “Use as featured image” link.

The only thing left to do is make these featured images show up! You will need to edit the code for the loop in your theme’s files, which is usually found in index.php or in some cases in loop.php. Look for something like this:

<?php while ( have_posts() ) : the_post(); ?>
The code to display a post is inside here, it can be quite long
<?php endwhile; ?>

Wherever you want to show the images, add the following in the loop:

<?php the_post_thumbnail(); ?>

In some cases, you may want to show the featured image at a size different than the default. If so, you can pass the desired size as an argument, like so:

<?php the_post_thumbnail("wider_image"); ?>

You can name a size that you have previously created using add_image_size(), as I have done above, or you can use an array to specify a size on the fly: array(225, 166).

Creating Galleries Link

The easiest way to show multiple images in a post is to upload the images to the post and then use the gallery shortcode to display them all.

The settings pane for creating a gallery in WordPress7

Simply open the “Upload/insert” media screen, click on “Galleries,” and scroll down to the gallery settings. Make sure the links point to the attachment pages (more on this later), and then insert the gallery. Now, thumbnails of all the images you have uploaded to that post will be displayed, each linked to its attachment page.

Including and Excluding Images Link

You can easily include images from other posts or exclude certain images from the current post by modifying the gallery shortcode. If you switch the editor to the HTML view, you should see [ gallery ] where the gallery would show up. You can add options to it using the following format: [ gallery option_1="value" option_2="value" ].

To include a specific image, you will need to know its attachment ID. You can find that by going to the “Media” section of the WordPress admin area, finding the image you need, hovering over it, and reading the target from the URL or status bar. It should be something like The number after attachment_id is what you need.

You can include multiple items like so: [ gallery include="23,39,45" ]. And exclude items the same way: [ gallery exclude="87,11"].

Sometimes you will want to use all of the images attached to a post except the featured one. You could find the ID of the image and enter it in the exclude options of the gallery shortcode every time, but that would be a hassle (especially if you change the featured image later). Let’s automate this.

Regrettably, the only way to do this is by replacing a core function in WordPress with our own, using the remove_shortcode() and add_shortcode() functions. The large chunk of code below may be off-putting, but implementing it is as easy as copying, pasting and adding two lines of code. The reason we need to add all this is that we can’t just go around editing a WordPress core file; we need to replace core functions with built-in functions.

First, open your theme’s functions.php file (if it doesn’t exist, simply create it), and add the following code to it:

// remove the  WordPress function
remove_shortcode('gallery', 'gallery_shortcode');
// add our own replacement function
add_shortcode('gallery', 'myown_gallery_shortcode');

This removes the gallery_shortcode() function that WordPress uses to display galleries and replaces it with our own function, called myown_gallery_shortcode().

The code below is almost exactly the same as the default, but we are adding a line to exclude our featured image. Paste the code below into the functions.php file, and then read the explanation further down:

function myown_gallery_shortcode($attr) {
  global $post, $wp_locale;

  static $instance = 0;

  // Allow plugins/themes to override the default gallery template.
  $output = apply_filters('post_gallery', '', $attr);
  if ( $output != '' )
    return $output;

  // We’re trusting author input, so let’s at least make sure it looks like a valid orderby statement
  if ( isset( $attr['orderby'] ) ) {
    $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
    if ( !$attr['orderby'] )
      unset( $attr['orderby'] );
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
    'id'         => $post->ID,
    'itemtag'    => 'dl',
    'icontag'    => 'dt',
    'captiontag' => 'dd',
    'columns'    => 3,
    'size'       => 'thumbnail',
    'include'    => '',
    'exclude'    => $default_exclude
  ), $attr));

  $default_exclude = get_post_thumbnail_id($post->ID);
  $exclude .= ",".$default_exclude;

  $id = intval($id);
  if ( 'RAND' == $order )
    $orderby = 'none';

  if ( !empty($include) ) {
    $include = preg_replace( '/[^0-9,]+/', '', $include );
    $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

    $attachments = array();
    foreach ( $_attachments as $key => $val ) {
      $attachments[$val->ID] = $_attachments[$key];
  } elseif ( !empty($exclude) ) {
    $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
    $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  } else {
    $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

  if ( empty($attachments) )
    return '';

  if ( is_feed() ) {
    $output = "n";
    foreach ( $attachments as $att_id => $attachment )
      $output .= wp_get_attachment_link($att_id, $size, true) . "n";
    return $output;

  $itemtag = tag_escape($itemtag);
  $captiontag = tag_escape($captiontag);
  $columns = intval($columns);
  $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  $float = is_rtl() ? 'right' : 'left';

  $selector = "gallery-{$instance}";

  $output = apply_filters('gallery_style', "

n”; return $output; }

In lines 18 through 29, WordPress is determining the default attributes. By default, nothing is excluded; so under this bit of code, we add two more lines, and that’s it:

$default_exclude = get_post_thumbnail_id($post->ID);
$exclude .= ",".$default_exclude;

The first line here finds the featured image of the post in question, while the second appends it to the exclude list. The rest of the code is the same as the default.

Using Attachment Pages Link

A WordPress attachment page with an image, a description and some meta data8

In my opinion, attachment pages are the single best tool for creating richer, more informative image-driven websites. They enable you to create separate pages for each and every media item you have, affording you considerably more power in managing them.

Attachment pages exist in WordPress by default, but people seem to rarely link to them. Linking thumbnails directly to their full-sized versions (i.e. without the website framework) is much more common. I am not a huge fan of this because it throws the user into a completely new environment without prior warning. Attachment pages allow you to show the user a wealth of information about the image; and for those who need a bigger version, you can display download links for different sizes.

Enabling Attachment Pages Link

As stated, you don’t need to do anything to enable attachment pages. Just make sure to link your images to them instead of to the original files. For galleries, link to the attachment page using the radio buttons before inserting them. When inserting a single image, point the link’s URL field to the “Post URL” by clicking the relevant button below it.

Styling Attachment Pages Link

If your theme doesn’t have an attachment.php file, then single.php will handle the display of attachment pages by default. If you have a decent theme, chances are this will work fine without your needing to touch any code. When clicking on an image, you should arrive on a page that shows the title and description of the image and the image itself.

To add additional information to this page, you will need an attachment.php file. I suggest duplicating single.php and going from there, because in most cases it will have most of what you need.

Adding Image Data Link

To make the attachment pages more informative, add a bunch of meta data to your images. To help with this, I have created a plug-in especially for Smashing Magazine readers, which you can download from the WordPress Plugins9 page, or just search for “advanced custom fields” in WordPress’ back end where you “Add new” plug-ins.

This plug-in lets you create your own custom fields, like the photographer’s name, coordinates, color palette, etc. What you add is up to you. You can easily manage all of the information on the plug-in’s admin page.

In the video below, I’ll walk you through how I did this on my own blog. You’ll learn about basic usage and see an example.
Better Media Management With WordPress Using the Media Custom Fields Plugin10,” by Daniel Pataki11.

Creative Attachment Page Uses Link

Using the add_image_size() function mentioned above, you could create five or six image sizes and show Flickr-style download options that allow users to choose the dimensions of their preference. This is helpful when showcasing desktop backgrounds and large photographs. So, let’s do that:

// If we are on an attachment page, the $post object will be available and the $post->ID variable will contain the ID of the image in question.

// Find the meta data field from the postmeta table, which contains the sizes for a given image. This is the '_wp_attachment_metadata' field, which contains a serialized array. Take care, because if you use 'true' as the third parameter, the function will unserialize the string for you, so that you don’t need to do it.
$image_meta = get_post_meta( $post->ID, '_wp_attachment_metadata', true);

// Put all the image sizes and file names into an array for ease of use
$image_sizes = $image_meta['sizes'];
$image_sizes['original']['width']  =  $image_meta['width'];
$image_sizes['original']['height'] =  $image_meta['height'];
$image_sizes['original']['file']      =  $image_meta['file'];

// Display a list of links for these images
echo '
<h3>This image is available in the following formats</h3>
echo '
        ‘; foreach ( $image_sizes as $size_name => $size ) { $url = wp_get_attachment_image_src( $post->ID, $size_name ); $anchortext = $size[‘width’] . ‘x’ . $size[‘height’]; echo “



    “; } echo ‘


Adding Color Palettes Link

By adding some creativity to the mix, you can come up with some nifty features. The screencast above and the code below shows you how to display color blocks of the dominant colors in each of your photos.


To accomplish this, you will first need to create a custom field using the Media Custom Fields plug-in and name it something like “Color Palette.” Remember to look at the field name that the system generates; it is displayed in parentheses next to the title you chose. It should be something like tqmcf_color-palette.

Once that’s done, edit the image you’d like, and add the following in the custom field: color_1,color_2,color_3, where colors_x should be hex values. In my case, I entered the following string: f0e9bf,e4dc99,000000.

Open up the attachment.php file in a code editor. Wherever you want to display the colors, you’ll need to add something like this:

// Retrieve the field value from the database
$color_palette = get_post_meta( $post->ID, 'tqmfc_color-palette', true );

// Turn the string into an array of values, where each value is one of the colors
$colors = explode( ',', $color_palette );

echo '
<h2>Logo Colors</h2>

// Loop through all the colors and create the color blocks, which will actually be links pointing the the color's page on
foreach ($colors as $color) {
    $link = ''.$color.'/';
    echo '';

You will also need to style the link element so that it shows up. Because anchors are inline elements by default, if they have no content, they won’t show up. Here’s the CSS I used, but you’ll need to change it to match your website:

.color-block {
    display: block;
    float: left;
    height: 20px;
    margin-right: 3px;
    width: 30px;

Conclusion Link

As you can see, even with minimal effort, you can create a much more robust system for storing and showing images. And with some copying and pasting, you can take it one step further.

The first and most important step is to add meta data like alt text to images, give them meaningful file names and so on. By doing so, you lay a foundation for any media management system. You can easily add other meta data to your files by using the Advanced Custom Fields14 plug-in for WordPress.

With this foundation in place and a few simple code tweaks, you can show images based on any of the custom fields you wish, displaying relevant and interesting information about them. Creating download buttons for multiple sizes and creating multiple color palettes are only the tip of the iceberg. The techniques showcased here can be used for so much more!


Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12 ".$link[0]."
  13. 13
  14. 14

↑ Back to top Tweet itShare on Facebook

Hallo, my name is Daniel :) I build plugins, themes and apps - then proceed to write or talk about them. I contribute to various other online sites. When not coding or writing you'll find me playing board games or running with my dog. Drop me a line on Twitter or visit my personal website.

  1. 1

    Great post. It really help me to understand more on managing images in wordpress blog

  2. 2

    good post ;) helpful

  3. 3

    Hope I’m not being pedantic, but the correct terms are ‘alt text‘ and ‘title text‘, not tags. There is no ‘alt tag’, and the ‘title tag’ is used for the page title.

    • 4

      Vitaly Friedman

      May 26, 2011 6:29 am

      You are right. Thanks for the heads up, Adam. It’s fixed now.

    • 5

      Daniel Pataki

      May 26, 2011 6:49 am

      Hi Adam,

      Thanks for pointing that out, since there is such a thing as a ‘title tag’ it’s a pretty big error, thanks Vitaly for taking care of it.

      Just to clarify this, “alt” and “title” are attributes of the “img” tag.

    • 6

      Thank you for pointing that out, it does infuriate me when people use “tag”. And as Daniel said they are “attributes” of the tag, rather than tags themselves, or text. The text would be considered the value of the attribute.

      However, great article!

    • 7

      Well, you are wrong, too. It’s actually alt attribute and title attribute, nothing else :P

      cu, w0lf.

  4. 10

    Good article !

    You can also download my plugin :
    You can register/unregister or override your thumbnails sizes, you can regenerate the files for the images and finally the sizes registered appears in the post image insertion box.

    • 11

      Very good image sizes manager.
      Tested and appoved ! Thanks Rahe !

      Thanks for this article !

  5. 12

    Adam- Yes, you are being pedantic.

    Great post. Will be a nice reference when building my WordPress sites.

  6. 13

    Great post!

    I hope I’m not been too naive, but one of the stuff that should be included is how to use the first image in your post as a thumbnail image.

    Most of sites where all the users with no editorial skills posts (like a blog community) have a feature to collect the first image and display it in their home page like do.

    Is there a simple way to make it? Or we need plugins for that?

    • 14

      Daniel Pataki

      May 26, 2011 7:04 am

      Hi Dorival,

      I completely agree with you, I should have though of putting this in. There is a rather big issue when using the first image as a featured image.

      Making something a featured image, as in an image recognized by WordPress as a featured image, requires an action. In other words, when you upload an image and set it as the featured image, you are setting image 265 as the featured image manually and that’s that, it’s not dynamic, as in it does NOT pull the first image from a bunch of images.

      Despite this, it is possible to add an action using a hook to the upload. This hook will run after your upload, and if no other uploads are detected, it would make the current one a featured image. This image would be the featured image from then on, if you delete the image, there will be NO featured image for the post, as opposed to pulling the earliest uploaded one.

      So method one would be to create such a hook, meaning you will definitely need a plugin for this (or some custom coding on your part).

      Method two is to use your own ‘featured image’. This also requires some custom coding. Where you want the featured image to appear, you would need to pull the earliest uploaded attachment’s url, and put it in an image tag.

      I would strongly suggest method 1, since it gives you much more power. I am not aware of any plugins which would do this, if I see a lot of requests I will try and create one quickly :)

    • 16

      You can add this function in functions.php file to pull the first image of the post:

      function catch_that_image() {
      global $post, $posts;
      $first_img = ”;
      $output = preg_match_all(‘//i’, $post->post_content, $matches);
      $first_img = $matches [1] [0];

      if(empty($first_img)){ //Defines a default image
      $first_img = “default.jpg”;
      return $first_img;

      Then in the files where you want to display that first image, add this:

      echo catch_that_image(); inside the img tag and php tag.

      For posts without an image, the theme will display the default.jpg.

      • 17

        Daniel Pataki

        May 26, 2011 12:22 pm

        Hi Phe Le,

        I think in some cases this would defeat the purpose, since what you’re doing is parsing the image out of the post content itself. in many cases I think what people want to do is to upload an image, but not insert it into the post, and have it as a featured image. Also, I am not a big fan of preg_match in these situations, since heaven knows when that will stop working due to changes, it’s not very future proof.

        I suggest querying the database for attachments of a post and displaying the first one. On a not very good at all level, this would be something like:

        $image_id = $wpdb->get_var(“SELECT ID FROM $wpdb->posts WHERE post_parent = $post->ID AND post_mime_type LIKE ‘image%’ ORDER BY post_date DESC LIMIT 0, 1”)

        This will retrieve the ID of the first image uploaded. You can then use
        wp_get_attachment_image( $image_id, $size) to show the image, where size is either a predefined size name, or an array containing the width and the height (see article).

        You could also use get_posts, I prefer the query above because it only gets the ID, which is all we need, so it is a bit more efficient.

        • 18

          Hi Daniel Pataki,

          Yes, I personally would rather use the featured image from WordPress 3.0 and add_image_size too. However, to reply to Dorival about a simple way to use the first image as a featured image, the solution above works fine, especially when the site already has many posts. It would take a lot of time to add featured image to every post. To resize the images, you can always use timthumb to do it.

          • 19

            Daniel Pataki

            May 27, 2011 12:37 am

            Hi Phe Le,

            Oh yes, I wasn’t saying it wouldn’t work. In many cases it is a luxury to use the best solution, doing something that just works is fine in a lot of cases. I agree that in some cases the easiest thing is to just use your solution :)

    • 20

      Mark Simchock

      June 2, 2011 7:50 pm

      I’d have to think about it a bit more but off the top of my head the easiest solution might be to just parse the_content() and find the first image that way.

      That being said, I’ve been working on a new theme in my spare time and just went through an exercise with images. I ran into a couple interesting things that I’ll mention below. Dorival if you want to email me I might be able to work up a quick function for you.

  7. 21

    Howdy! Great article, but I was also hoping you would cover a plugin or method for creating a post for a bunch of photos at once. I’m setting up a photo blog, so do I have to create a post for each piece of media I upload if I want them to show up on my portfolio?

  8. 22

    Matt Rittman

    May 26, 2011 7:12 am

    Wow, great post! Very informative. I think you could have gone a little more in-depth with the WordPress Galleries but it’s all good. I wish you could add multiple galleries to a page but there’s not a way unless you use a plugin from what I understand…

  9. 23


    Is there a way to attach image to multiple posts? I’ll use the same image with its own data in different post but apparently i need to re-upload the same image more then ones and add all the image-data again to be able to add it in the gallery?


    • 24

      Daniel Pataki

      May 26, 2011 8:07 am

      Hi mrmema,

      It would be extremely useful if there was, I completely agree, but regretfully, right now it s not available out of the box. You could achieve what you need through some custom coding or a plugin though.

      Doing it by uploading the image multiple times is extremely bad practice, but alas there is no better way.

      What you would need is either a table sotring which attachment is for which post, or you would need to use a serialized array to store it in the postmeta table.

      I completely feel your pain though, it is a shame that this isn’t implemented yet.

    • 25

      Yes there is, just go to upload an image and select the “Media Tab”, search for your image with the “Search Media” field and then select it from the list. There is no need to upload the same image twice.

  10. 26

    Great stuff. Thanks for the detailed descriptions and the code examples. I am working on a site now where I need thumbnails in 80×80. I will use the resizing tips you gave to make that happen!

  11. 27

    I’m not sure the title attribute should be used with so little thought. Refer to this post from the RNIB’s “Too Much Accessibility” series:

    • 28

      Daniel Pataki

      May 26, 2011 1:38 pm

      I don’t necessarily agree with everything he’s saying, but there are more valid points in there than ones I don’t agree with for sure. Specifically in this scenario he says alt and title attributes are not good on images because they can distract dyslexic users.

      While certainly true, they do benefit the visually impaired. If the title and the alt attribute are identical, this is obviously a waste, but I suggested a different sort of usage.

      This is actually a very interesting usability point here, which I haven’t thought of. I believe that too much information for the blind is good, because this is how they form a mental picture. However, excess information is not great for dyslexia.

  12. 29

    Angelo Barovier

    May 26, 2011 10:16 am

    I love learning me something new about WP, especially when the learnin’s made so darned easy. Kudos, good sir!

  13. 30

    Friggin’ sweet! I skimmed over a lot of this, but the last two goodies really got me thinking. For all the fun tricks out there people are using with WordPress, I’d never thought to even do the multiple images linking, yet it’s such a simple idea. The color palatte wouldn’t be appropriate for every type of website, obviously, but it’s a great idea for anyone with a design blog. You could even use something like that for things like fashion or home decorating blogs.

  14. 31

    This article came just two days after it should have. Had some trouble with gallery_shortcode just a couple days back. Nice to see a great article including this as well…

  15. 32


    Another fun and interesting way to manage the images on a WordPress blog:

    • 33

      Daniel Pataki

      May 27, 2011 2:27 am

      Hi Mihai,

      I didn’t try the plugin, but based on the video on your site it looks VERY promising. I’ve always found the WordPress media things a bit clunky, while so much better alternatives could be available.

      Perhaps we could work together later to merge the media custom fields plugin into yours, or vice versa :)

  16. 34

    Couldn’t that long chunk of code in the middle to remove the post thumbnail from a gallery be replaced by a simple filter on the post_gallery hook?

    I’ve not had a chance to produce the exact code that you’d need but I reckon that would be a much better way to achieve that effect.

    • 35

      Daniel Pataki

      May 27, 2011 2:22 am

      Hi Ross,

      yes indeed it could, good point. The reason I chose to go with modifying the shortcode itself is to be able to use all the options available to us.

      The post_gallery hook runs inside the shortcode hook, line 8 above, and if it contains any output, it uses that and does not run the rest of the code in the function. If you are looking to one thing, than you could code it in a much shorter fashion. However if you still want to be able to have defaults, override them and so on, you need the rest of the function anyway. Also, the shortcode contains all the right code for putting things into columns and so on, you would need to code this yourself if you used the post_gallery hook.

      I think my example is better suited for people just starting out with hooks, while your method would be better suited to developers who know exactly what they need and how they need it.

      • 36

        Ah yes. I see what you mean. Sorry, I’m rushing through my reading list and didn’t quite look at the code properly. I confess I saw you’d written 100 lines of code and thought “All that just to change the exclude attribute?”

        Some WordPress functions have filter hooks on the attributes (like the widget_tag_cloud_args hook, where WP does:

        wp_tag_cloud( apply_filters(‘widget_tag_cloud_args’, array(‘taxonomy’ => $current_taxonomy) ) );

        Would be good if there was a post_gallery_args filter hook so we could just do something like:

        add_filter(‘post_gallery_args’, ‘aaa_remove_featured_from_gallery_args’);

        • 37

          Daniel Pataki

          May 27, 2011 3:24 am

          I completely agree, although you could argue, that if you start writing hooks for every attribute, globally it is more efficient if you just write your own code. i think at this technical level it is easier to write your own stuff, but in any case i suppose it’s a matter of balance.

          Since the hundred lines of code are just duplicate from WordPress it really would make it much nicer if we could just change the exclude attribute :)

  17. 38

    Thanks for this article. I sometimes wonder if WordPress can be as good at managing images as it is at managing text. This helps convince me it can be.

  18. 39

    tajwali khan

    May 27, 2011 10:26 am

    Thanks for this article. I sometimes wonder if WordPress can be as good at managing images as it is at managing text. This helps convince me it can be.

  19. 40

    Christopher Anderton

    May 27, 2011 10:37 am

    No news for me, except the color palette trick. Pretty nifty.

  20. 41

    How would you do this? You have a gallery of let’s say five images. Using a light box plugin you can flip through these five images. Now I’d like to have only the first image of the gallery visible because that’s where the user clicks to start the lightbox. He/She doesn’t need any other images in the post itself, just the one to start. But my lightbox needs the other a hrefs with rel=”lightbox” to actually find the images.

    Comments appreciated.

    • 42

      Daniel Pataki

      May 27, 2011 1:51 pm

      Hi Francis,

      This would require some custom coding, since you will either need to modify the shortcode like I did in the example, or write your own thing.

      Without knowing more it’s hard to say how you would start, but if you have all the images in a div (#images) you can hide all img elements inside that div using css and then do something like this with jQuery:

      jQuery(“#images img:first”).show()

      Perhaps a better approach would be to actually show all the images, but then hide all but the first. This way, if someone doesn’t have javascript enabled, they would still get to see the images.

      jQuery(“#images img:not(:first)”).hide()

      Obviously a LOT more work is needed, and this may not be the best approach for what you have in mind, but it’s a start :)

  21. 43

    Really useful post – thanks Daniel/Smashing! I’ll be acting on the guidance given. Cheers

  22. 44

    How do we create an ‘index’ of thumbnail images of other pictures for the post on the attachments.php page?

    • 45

      Daniel Pataki

      May 28, 2011 9:43 pm

      Hi Alvin,

      If I understand correctly, what you want is this: If you click on an image in post 657, you go to the attachment page, which normally shows only the image you clicked on. However, you would like to show that image, and all other images attached to post 657?

      If this is the case, your job isn’t that difficult. On the attachment page, the details of the image are stored in the $post variable. This includes the post_parent value, which is stored in $post->post_parent, this is the ID of the post the image is attached to.

      From there you can use the first example from the get_posts() function example in the WordPress Codex under “Show all attachments”, just head on over to

      Make sure to use ‘post_parent’ => $post->post_parent instead of ‘post_parent’ => null.

      You could also use the following code to grab just the ID of the images:
      $images = $wpdb->get_col(“SELECT ID FROM $wpdb->posts WHERE post_parent = $post->post_parent AND post_type=’attachment’”)

  23. 46

    Jeff Lambert

    May 29, 2011 4:12 pm

    Excellent post. Thanks for sharing the code as it adds to my toolbox and furthers my ability to build my sites to a higher level.

  24. 47

    Think you might have made a mistake here: ” And exclude items the same way: [ gallery exclude=”87,11″ include=”23,39,45″ ].”
    You can’t use the include and exclude attributes together! Doesn’t make any sense and isn’t allowed!

    • 48

      Daniel Pataki

      May 31, 2011 3:09 am

      That is exactly right, thanks for pointing it out. I think I just copy pasted the include example by mistake. The error is now corrected, thanks again!

  25. 49

    Great learning. Thanks.

  26. 50

    Hi Daniel,
    Yesterday I installed the plugin to optimized the images on my site but it changes considerably their colors.
    What would you recommend to help a site faster without compromising quality?

    Thanks for your great article!

  27. 51

    Matt Ritter

    June 1, 2011 1:12 pm

    Thanks Daniel! This is a fantastic post. WordPress has so many features that some of us have no idea about. Wow, this is going to help!

    • 52

      Yes, WordPress is extremely awesome, and I guarantee you, the more you code the more you will think this :)

  28. 53

    Hi Olivia!

    I am not really an image optimization expert, but I find that making sure that if you show a 300×200 you actually load a 300×200 image (as opposed to scaling down a 1200×600 image) is well enough.

    Using the PHP GD library will give you the power to create automatic image manipulation routines, but that requires some PHP knowledge and considerable coding.

    Also, if you are optimizing images that are used by your theme, one good method is to use sprites. Instead of loading 20 images for your theme (the nice arrow image for your lists, the gradient on your button, the submit button graphic, etc), you just use one image which contains all these graphics. Take a look here:

  29. 54


    June 2, 2011 2:00 pm

    That is alrealy epic post

  30. 55

    Ok. So here’s another image related question. Thinking about group blogs, where the writers aren’t very well versed as being techies :), is there a plug-in where after they chose the category that the post was going to go in, it could just display all of the potential images related to that category. I.E. A blog post about old cars would be categorized under CARS and then there would be a specific gallery where the images have been uploaded that would potentially fit with those kinds of posts? THat way the individual blogger wouldn’t have to upload an image at all but choose from a lsit that was already relevant.

    Make sense?

    Thanks for your input!

    Twitter: @passionmuse

  31. 56

    Mark Simchock

    June 2, 2011 7:53 pm

    Two things I’d like to add

    1) WP actually stores attachments as posts.

    2) For reasons I don’t understand, the title attribute is the post title, the excerpt is the description (I think) but what’s odd is the attachement’s alt value is stored in the post meta. I kinda figured alt would be available directly.

    • 57

      Daniel Pataki

      June 3, 2011 5:35 am

      Hi Mark,

      Thanks for 1, I have no idea why I did not mention this. Since WordPress is now a CMS, not a blog management app, it should be mentioned that it is better to think of the posts table and posts in general as “content” instead.

      I think the chief reason for setting up attachment data storage the way they did was exactly for attachment pages. The description of the image is stored in the post_excerpt area because it is likely a shorter text. The post_content is reserved for a longer chunk of text written especially about the image.

      The case then becomes that you can’t really put the alt value anywhere else. In any case, it can easily be retrieved directly using get_post_meta() and it is also available if you use any of the built in attachment retrieving functions.

      • 58

        Mark "Chief Alchemist" Simchock

        June 8, 2011 10:55 am

        Hey DP – Two more things

        1) I guess I just expected alt= to be more “accessible” seeing that it’s required in the mark up.

        2) I tossed together a primer on some things I’ve bumped into lately while I was going some WP and images discovery. It’s not as thorough or as pretty as your article but I think some might find it helpful.

        Let me know what you think.

        btw, what syntaxhighlighter plugin do you use here? I’m having a bit of a struggle with mine at the moment. Maybe it a cache issue?

  32. 59

    Anders Ekkje Slettebø

    June 2, 2011 10:14 pm

    Great article. I have always linked an image to the image, not the attachment. But it would be really nice if the attachment page showed a link to the previous and next image in the gallery. Is this possible?

    • 60

      Daniel Pataki

      June 3, 2011 5:41 am

      Hi Anders,

      That is indeed a good idea, and yes, it can be done. When on an attachment page, all you need to do is find the parent post of the particular attachment shown. Then retrieve the attachment just before the current one from the database and the one just after and show them as links.

      You can find the attachment’s post parent by simply using the $post->post_parent variable. You can then do something like this to retrieve the previous attachment:

      $prev = $wpdb->get_var(“SELECT ID FROM wp_posts WHERE post_parent = $post->post_parent AND post_type= ‘attachment’ AND ID < $post->ID LIMIT 0,1″)

      You can find the url for this by using:

      I want to quickly mention that the code above just finds the image with a lower ID than the current one. You can also use post_date to get a more accurate result.

      A bit more work is needed here obviously, but these are the major steps needed.

  33. 61

    Great article with alot of good and relevant tips, I found it well and explained and massively useful. As with all info these days, open up for knowledge and use only what you need.

    Job well done!

  34. 62

    Thanks for sharing this article and discussions happening here are equally valuable. Being a regular visitor to Smashing magazine, I was on the lookout for tips to enhance user experience on my first blog that shares free textures. Most of the blogs / sites are text-rich hence the tips here are much appreciated.

    Creating separate links for images and alt attributes is a good suggestion, easy to follow than tweaking the code.

    I’m using wordpress, however the thumbnails it generates are of unequal sizes, is there a way out to maintain the thumbnail sizes?

    • 63

      Daniel Pataki

      June 8, 2011 1:42 am

      Hi Anjali,

      If you aren’t using any custom settings, go to the media settings in the WordPress backend and you’ll see three settings for thumbnails. Where it says “thumbnail size” you can choose to crop an image to an exact size. Normally when an image is downscaled it retains its aspect ratio. An exact crop will make sure your images is x wide and y high, but to do so, it will probably need to cut some of it off.

      If those settings are not sufficient you can define your own, just see the article above on how to do it. Make sure to add “true” as the last parameter when defining an image size and all your images will be the same size.

      • 64

        Thanks Daniel, I’ll try this out, along with other tweaks you have suggested in this article.

  35. 65

    Awesome, so much useful info. Yer the best!!!

  36. 66

    Hi Daniel,

    Thanks for a great article. I am taking a lot to use for my theme development.
    Also is the code on line 8 and 9 under “Creative Attachment Page Uses”, correct ?
    The width value is fed twice.

    Cheers :)

    • 67

      Daniel Pataki

      July 19, 2011 4:30 am

      Hi Sidd, thanks, and well spotted!

      I have corrected the error, thanks so much

  37. 68

    Nice article, thanks.

    How about adding tags to media? Does anyone know a good tutorial on that?

    • 69

      Daniel Pataki

      July 19, 2011 4:34 am

      Hi Koen,

      This is the same issue as custom fields, there is really no reason you shouldn’t be able to do this, WordPress supports it for sure. Any attachment is stored in the posts database, just like actual posts, so it wouldn’t take too much time to code it it.

      If you want to do it yourself, you way want to take a look at wp_set_object_terms() which will probably let you do it

  38. 70

    Great article about handling images. I just have one question, since i’m not really good in php. I added the download links for image sizes, but it is showing all the images sizes I added (thumbnails, default featured post size, etc.).

    How can I alter it that it will only show a selected scope of images sizes (such as default, 1920*1280, 1650*1080, etc.).


    • 71

      Daniel Pataki

      August 30, 2011 5:05 pm

      Hi Michiel,

      I haven’t tested this, but you can try the following. Extend the foreach loop which starts on line 20 like so:

      $sizes_to_show = array(“1920×1280”, “1650×1080”);
      foreach ( $image_sizes as $size_name => $size ) {
      $url = wp_get_attachment_image_src( $post->ID, $size_name );
      $anchortext = $size[‘width’] . ‘x’ . $size[‘height’];

      if(in_array($anchortext, $sizes_to_show)) {
      echo ““.$anchortext.”“;

      This is far from a perfect solution, but it was the quickest way to quickly modify the thing. If it throws an error let me know and I’ll modify it :)

      • 72

        Thank for the extend! It won’t show any results however when I extend the foreach loop, but i’ll look more deeply into it later.

  39. 73

    Nice post! I’m creating a portfolio site with wordpress, and these informations is all i need at this moment =)

  40. 74

    Really interesting post. One which I will definitely be using in the near future.

    Where you are selecting a featured image for thumbnails for a post – can you choose an image as a featured image and use it full size?

    Are there any plugins for doing this using Flickr?


  41. 75


  42. 76

    Great post –

    I’ve come to love another plugin called Multipost Thumbnails, which allows you to have more than one “Featured Image”, which becomes a nice way to designate different photos for different purposes. Lots of posts have both a thumbnail, then maybe a hero image on the top that have different cropping or treatment, and it’s nice to be able to distinguish the two from the user’s perspective. These are also assignable to custom post types and specific image sizes, as well.

    I am currently looking for a good way to use the WordPress rich text editor and uploader functionality for custom admin pages and custom widgets. There exists a plugin for WYSIWYG widgets, but it’s buggy at best. I consistently use custom admin edit screens with custom inputs, many of which would be beneficial to use the upload modal and have the uploads’ image sizes generated just as in posts.

    Albeit hacky, I’ve used the thickbox upload modal to upload images on a custom admin page, but it doesn’t go through the usual PHP squishing into all of the custom image sizes. Nor do these attachments get entered into the database like other attachments. Any thoughts, ideas?

    • 77

      Daniel Pataki

      October 2, 2011 3:15 pm

      Hi larf2k,

      I believe I read a good tutorial on using the uploader on custom pages, I think it was this one though I’m not sure.

      It’s my experience that putting the image uploader anywhere is pretty easy, but putting the WYSIWYG editor anywhere is much more difficult. I am also experimenting with the same things and I’ve managed to pull the image uploader off in a completely non wp admin environment.

      It is also possible to put the WYSIWG editor in but there are so many factors involved (proper functions, css, js, etc) that it just proved to be too much of a hassle and I went for a custom editor.

      Do let me know if you get anywhere with the WYSIWYG editor, I just don’t have the time to look into it but I would be very interested to hear if you can do it easily.

  43. 78

    Excellent post! I didn’t realize that you can add more sizes via functions.php, I thought I was stuck with the default 3.

  44. 79

    A very interesting article, thanks for sharing!

  45. 80

    Douglas Peterson

    November 26, 2011 9:58 am

    This might relate to alvin’s comment (5/28/2011), but I’m not sure:

    In a site I’m creating for a photographer, I want to accomplish two things in certain blog posts (not pages):

    1. I want to create posts where there are a number of thumbnails that each click through to a larger image. With the WP Gallery shortcode, you click through to a pre-defined larger image for which you have little control (that I can figure out, at least) so I think your reply to alvin says you can instead change those links to specific attachment pages. Is that correct?

    Further, once you reach those attachment pages, it there a way to make a loop of all the attachment pages linked to the original post’s thumbnails so a visitor can skip through the larger versions of the thumbnails with “Previous” and “Next” buttons automatically added to the attachment pages?

    2. At other times, I want to have posts where there is only one image but clicking on the headline of that post would take the viewer to a page of thumbnails related to the original image. Then, on the page of thumbnails, if an image is clicked, it would take the visitor to a larger version of the image that would be in a loop with all the other larger versions with “Previous” and “Next” buttons for that particular group of images along with a link to jump back to the thumbnail page. Is that possible?

    If you have the time to explain it, be gentle. I’m a designer not a coder with only limited experience in modifying WP code.

    Thanks for any help you can provide.

  46. 81

    Line 23 in “Download Links for Image Sizes” seems to be wrong. I think the href should be “$url”.

  47. 82

    Is there any disadvantage from serving images from an image folder within the your theme directory as opposed to using the media uploader?

    Still using correct html, but bypassing the media uploader all together.


  48. 83

    Incredible stuff, thank you!!!

    I have one question about the code to print the various image size links (flikr style). When I drop this code into my image attachment page, I get a list of all my image dimensions, but just text, no permalinks. Am I missing something?

  49. 84

    Phill Chambers

    July 29, 2013 8:39 pm

    Great article, thanks Daniel. Very informative & helpful.

  50. 85

    Thanks Daniel. I am newbie to wordpress blog and I confused alt ,caption,title of images to be added for my website Not could be able to do it properly .Thanks again for the clear info.

  51. 86

    Sorry now could be able to do it

  52. 87


    Thanks for an informative article. I browsed fully, including the comments, I could not find anyone asking what I wanted to:

    When inserting a picture in a post, WordPress puts the size attributes. But not so when putting them in media library. Pagespeed from google is heavily dependent on it.

    How to add them automatically? I am sorry if I missed this somewhere above.

    (BTW, I have never seen such a long article without breaks or pages. NICE)

  53. 88

    I like your plugin but i was wondering if there was a way that i can apply the photographer name to the images one time and then it would apply to the images i am uploading at that time.

    I am asking this as i have 5000 images from 600 photographers to upload to my wordpress sites and i was hoping that you might have a way of doing this with your plugin or you would know of a plugin. Please let me know.

  54. 89


    I am trying to insert images through a php script. I want to attach them with my posts. I have added a new entry into wp_posts table, and they are showing in the post media. But images are not appearing. But images are in folder and I have checked that. I am not creating any thumbnails. I am just copying original size images. So, is there any way so that I can view images in media as well.


  55. 90

    How to add next / previous image links to the attachment page?

  56. 91


    March 15, 2014 9:46 pm

    Great article, thanks Daniel. I like your plugin.


↑ Back to top