Insert the Featured Image into the Post Content with Shortcode

Somebody asked today, how to insert a ‘featured image’, aka post thumbnail, into the content of a post.
Obviously this cannot be done with the usual WordPress function ‘the_post_thumbnail()’ as the php code would not get rendered in the post’s content.

For me, the best way seemed to be to programm a shortcode for this purpose;
in the most basic form this would be:

add_shortcode('thumbnail','thumbnail_in_content');
function thumbnail_in_content( $atts ) {
global $post;
return get_the_post_thumbnail( $post->ID );
}

However, this is not very user friendly and does not alllow for setting the image size and alignment.

Shortcodes allow for a number of attributes, so I integrated the attributes ‘size’ and ‘align’ to the shortcode, together with some validity checks and default values.

The usage for the [thumbnail] shortcode is, for example:

[thumbnail size=medium align=right]

or

[thumbnail size='array( 300, 200)' align=center]

Any input errors would revert to size= ‘post-thumbnail’ and/or align=’none’.

The final code – see pastebin ‘featured image in post – shortcode’

references:
http://codex.wordpress.org/Shortcode_API
http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
http://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes

4 Replies to “Insert the Featured Image into the Post Content with Shortcode”

    1. just in case – this is for a site based on WordPress.org only – not for WordPress.com blogs.
      you insert the few lines of code into functions.php of your theme (or child theme if you are working with one).
      insert the shortcode [thumbnail size=medium align=right] while writing the content for a post or page.

Leave a Reply

Your email address will not be published. Required fields are marked *