wordpress shortcode: smarterImage.

The issue: New layout had a 440px main column that restricted the overall size of images that could be shown. Previous theme had images uploaded at a much larger size, so they were being smushed and pixelated because new theme used max-width: 100%; markup to constrain their overall size.

The goals: Resize images to proper width and expand the main column on single pages so that they could take advantage of the larger images. Decided to create a shortcode that could take a unique identifier and return the medium sized or large sized image to take full advantage of the size of the layout. Also, dynamically pull the alt/title tag information from the db and allow that to be overridden by an inline param.

The code:

function smarterImage($atts, $content = null) {
   global $wpdb;
   extract( shortcode_atts( array(
      'imgid' => '0',
      'imgsize' => 'medium',
      'class' => '',
      'alt' => ''
      ), $atts ) );

   if (is_single()) { $imgsize = 'large'; }
   $imgclass = $class;
   $imgstring = wp_get_attachment_image($imgid, $imgsize, false);
   $imgsource = wp_get_attachment_image_src($imgid, $imgsize, false);
   $imgtitleqs = "select post_title, post_excerpt from wp_posts where id = $imgid";
   $imgtitleq = $wpdb->get_row($imgtitleqs);

   if (strlen($alt) > 0 ) {
		$imgtitle = $alt;
   } elseif (strlen($imgtitleq->post_excerpt) > 0 ) {
		$imgtitle = $imgtitleq->post_excerpt;
   } else {
		$imgtitle = $imgtitleq->post_title;
   }

   return '<img width="'. $imgsource[1] .'" height="'. $imgsource[2] .'" src="'. $imgsource[0] .'" class="attachment-'. $imgsize .' '. $imgclass .'" alt="" title="'. $imgtitleo .'" />';
}
add_shortcode("sImage", "smarterImage");

Usage:
[sImage imgid=”1467″ class=”” alt=””]

The imgid is required, all other attributes are optional.

Additional Notes: As with all other redesigns, I used the great Regenerate Thumbnails to create the new medium and large sized images. I also learned a good deal about shortcodes from Smashing’s piece on Mastering Shortcodes.

The best way to see how the shortcode works is to view the front page, or one of the previous pages and compare it to how a single page looks. take a look at how the post dynamically substitutes a max-width 420px image for a max-width 720px image. It’s easiest to see it with a post from the on repeat category.