WordPress shortcode: Automatically insert image by file name

July 15, 2009 at 9:48 am

Shortcodes are always a good solution when you need to achieve a specific task. In this recipe, let’s see how we can insert an image in a post, simply by using a shortcode and the filename.

The first thing to do is to paste this code on your functions.php file:

function image_shortcode($atts, $content = null) {
    extract( shortcode_atts( array(
    'name' => '',
    'align' => 'right',
    'ext' => 'png',
    'path' => '/wp-content/uploads/',
    'url' => ''
    ), $atts ) );
    $file=ABSPATH."$path$name.$ext";
    if (file_exists($file)) {
        $size=getimagesize($file);
        if ($size!==false) $size=$size[3];
        $output = "<img src='".get_option('siteurl')."$path$name.$ext' alt='$name' $size align='$align' class='align$align' />";
        if ($url) $output = "<a href='$url' title='$name'>".$output.'</a>';
        return $output;
    }
    else {
        trigger_error("'$path$name.$ext' image not found", E_USER_WARNING);
        return '';
    }
}
add_shortcode('image','image_shortcode');

Once done, you can use the image shortcode in your posts. For example, the following line of code:

[image name=cat]

Will insert (with all proper attributes) cat.png from the /wp-content/uploads/ directory.

Thanks to Rarst for his valuable contribution to WpRecipes!