6

Each post currently requires the featured image to be duplicated within the post several times.

Is there any way in which I could dynamically call the featured image back into the post rather than manually inserting the image again several times?

UPDATE

I would also like to be able to show the image's caption and permalink if possible.

  • The code supplied below has been great and works perfectly, but is there anyway to bring the cation text and post url through at the same time. I have searched around various places but cant seem to find a method of doing this. :( – Allan Jan 6 '16 at 11:26
8

Register the shortcode, ideally in a plugin or functions.php if you have to.

add_shortcode('thumbnail', 'thumbnail_in_content');

function thumbnail_in_content($atts) {
    global $post;

    return get_the_post_thumbnail($post->ID);
}

Add the shortcode to you post content.

[thumbnail]

If you want more features, see this post or the pastebin.


ADDING CAPTIONS AND LINKS

add_shortcode('thumbnail', 'thumbnail_with_caption_shortcode');

function thumbnail_with_caption_shortcode($atts) {
    global $post;

    // Image to display

    $thumbnail = get_the_post_thumbnail($post->ID);

    // ID of featured image

    $thumbnail_id = get_post_thumbnail_id();

    // Caption from featured image's WP_Post

    $caption = get_post($thumbnail_id)->post_excerpt;

    // Link to attachment page

    $link = get_permalink($thumbnail_id);

    // Final output

    return '<div class="featured-image">'
    . '<a href="' . $link . '">'
    . $thumbnail
    . '<span class="caption">' . $caption . '</span>'
    . '</a>'
    . '</div>';
}

RESOURCES

  • Thanks a million @jgraup - that worked perfectly first time for me. Is there anyway to really push this and get the displayed image to also pull through the image caption and post link as well. Thanks again. Allan – Allan Jan 5 '16 at 21:07
  • sorry thought i had closed it - :( cant find the option to set as answered or anything - only option is to delete it - :( – Allan Jan 13 '16 at 16:18
  • Thanks for the update on the code above, and sorry to be a pain but what would the shortcode be for this. I am currently using [thumbnail size='array( 150, 150)' align=right] but obs its not pulling through the caption or permalink. - thanks again - – Allan Jan 13 '16 at 18:53
  • I have read it, but will double check it. I would be happy to loose the size/align if i could get the other functions to work. :) – Allan Jan 13 '16 at 19:02
  • I am just checking it now, got the image and caption coming through. Just testing on features images from other posts. Sorry taking me a while to get head around the coding. Thanks for your help and advice, I have managed to actually learn something. ;) – Allan Jan 13 '16 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.