During the last week, the Ropardo Web Development Team has been working on a web portal based on the open sourced content management system Wordpress. I was given the task to create a new template for the new website which would eventually be populated with diverse information, ranging from static facts to fast changing local news.
wordpress-logo
One particular task that I had was to generate for every article / news an image thumbnail based on images within the article and in the case that the article didn’t had an image, to put a default thumbnail.

As all things with Wordpress, the task turned to be easy, I will show you 2 ways to do that.

1. Custom field method
The first method that I’ve tried was to put on every article a custom field called “thumbnail”
with the value containing the link to the source image. In the template, I would retrieve the value from the field and show the image with the help of get_post_meta method:

<img class="thumbs_box" src="<?php if(get_post_meta($post-&gt;ID, " alt="" />ID, "Thumbnail", true); else echo $DEFAULT_IMAGE; ?>" alt="thumbnail" />

Although the solution was simple and quick, there’s a big down side to this method. We want out web portal to be accessible to regular computer users so they can add themselves information to the website and that being said, the usability and friendliness of the backend has a crucial role. For example, a user that doesn’t know HTML would had difficulties finding the image path and adding a new custom field for the article. So that’s why I went on and searched for the second solution.

2. The attachment method
My idea was that the user should simply add images to an article and the thumbnail should be automatically generated from images in the article. The following code uses the method get_children to retrieve the attachments of a post with a certain ID:


<?php $images = get_children(array(
'post_type' => 'attachment',
'post_status' => null,
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'));
$attachment = null;
if(!empty($images)) : ?>
    <?php foreach ($images as $i) : ?>
        <?php $attachment=wp_get_attachment_image_src($i->ID, 'thumbnail'); ?>
    <?php endforeach; ?>
<?php endif; ?>
<img class="thumbs_box" src="<?php if(!empty($attachment) ) {$index = rand(0, count($attachment)); echo $attachment[$index];} else echo $DEFAULT_IMAGE_PATH; ?>" alt="thumbs" />

Where the variable $DEFAULT_IMAGE_PATH stores the path to the default thumbnail image in case the article lack images. For more information about Wordpress template development, check Wordpress Codex.