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.
Source: Blog wprecipes
Recent Comments