Tuesday, April 6th, 2010 | Adventures, Geek Out, Tips, Web Dev, WordPress

Helpful WordPress Shortcode – showthumbs

I was working on my daughter’s blog, which might be the most robust blog I’ve built, because it is my testing grounds for new features to add to WordPress sites/blogs. Tonight I added a neat kind of functionality, something I’d like to share.

Shortcode to show thumbnails.

Here’s how it works.

  1. Upload a bunch of images to a specific post, title the images whatever you like.
  2. Click “Save All Changes”. And Close. With this shortcode, there’s no need to “Insert Into Posts”. That will just waste time.
  3. Add the shortcode [showposts] to the content. It will drop in the thumbnails where you add the shortcode. The thumbnails will show in floated list format, side by side, with a 10px margin on the right and bottom (see the screenshot at the bottom).
// [showthumbs]
function showthumbs_func($atts, $content = null) { ?>
 <style type="text/css" media="screen">
 ul.photo-thumbs {
 margin: 0;
 padding: 0;
 }
 li.thumb {
 list-style: none;
 margin: 0;
 padding: 0;
 float: left;
 line-height: 0;
 margin-right: 10px;
 margin-bottom: 10px;
 }
 li.thumb.clr {
 clear: both;
 float: none;
 margin: 0;
 }
 </style>
 <?php
 extract(shortcode_atts(array(
 "showthumbs" => ''
 ), $atts));
 global $post;
 $pics = get_children( 'numberposts=-1&post_type=attachment&post_mime_type=image&post_parent='.$post->ID );
 $return='<ul class="photo-thumbs">';
 foreach($pics as $pic) :
 $image = wp_get_attachment_image_src($pic->ID, 'large');
 $return.='<li class="thumb"><a rel="slideshow" href="'. $image[0].'">'.wp_get_attachment_image($pic->ID, array(75,75)).'</a></li>';
 endforeach;
 $return.='<li class="thumb clr"></li></ul>';
 return $return;
}
add_shortcode("showthumbs", "showthumbs_func");

All you have to do to make this work is drop it in your WordPress functions.php file, located at root/wp-content/themes/your-theme/functions.php – if one doesn’t exist. Create one and wrap the code above in PHP tags.

I’m using colorbox to create a slideshow between them, all you have to do to accomplish this is install colorbox, and add this line to your head:

<script type="text/javascript">
 jQuery(document).ready(function() {
  jQuery("a[rel='slideshow']").colorbox({preload: true, slideshowSpeed: '2500', slideshow:true});
 });
</script>

Screenshot:

If you want to see this as a plug-in, leave a comment and let me know. I’ll do it. For real.

Discussion

  1. May 16, 2011

    Tambra says:

    Nice coding Joseph. Yes, please make this a plugin.

Leave a Comment