60 | Insert the Featured Image into the Post Content with Shortcode

g+

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

This entry was posted in Easy Coding for Wordpress, Tips & Tricks, WordPress and tagged , , , , . Bookmark the permalink.

5 Responses to Insert the Featured Image into the Post Content with Shortcode

  1. Salvador comments:

    I don’t know whether it’s just me or if perhaps everyone else encountering problems with your site.
    It looks like some of the text within your content are running off
    the screen. Can someone else please provide feedback and let me know if
    this is happening to them as well? This may be a issue with my internet browser because I’ve had this happen before.
    Many thanks

    My site Lensamovie

  2. Netshore comments:

    hello,
    is it possible to add an alt=”” attrib to the image ?

  3. Austen comments:

    On which page would I insert this code? Single.php ? Thanks

    • michael replies:

      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.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.