shortcode – wpv-image-caption

Sometimes it is usefull to output somewhere on the front-end the caption set on a Media image:

Media Caption

It is possible to create a custom shortcode to display the caption of an image:

// wpv-image-caption shortcode
add_shortcode( 'wpv-image-caption', 'image_caption_shortcode');
function image_caption_shortcode($atts) {
  global $wpdb;
  $url = $atts['url'];
  $id = $wpdb->get_var( $wpdb->prepare ("SELECT ID FROM $wpdb->posts WHERE guid=%s ORDER BY `ID` DESC", $url ) );
  $excerpt = get_the_excerpt($id);
  if($excerpt)
    return $excerpt;
  $attachment_meta = get_post_meta( $id, '_wp_attachment_metadata', true );
  if (isset($attachment_meta['image_meta']))
    return $attachment_meta['image_meta']['caption'];
}


Then I can use this shortcode anywhere passing an image url by the attribute “url”. The url can be a string or a Toolset image custom field shortcode:

[wpv-image-caption url="https://wp-customtypes.com/wp-content/uploads/my_image.jpg"]
[wpv-image-caption url="[types field='my_image' output='raw'][/types]"]


For example, it is possible to use the caption in a gallery created with a Toolset custom field with ‘multiple instances’.

[wpv-for-each field="wpcf-my-gallery"]
  <div class='my-thumb'>       
    [types field='my-gallery' title='%%TITLE%%' alt='%%ALT%%' size='thumbnail'][/types]
    <div class="my-caption">
      [wpv-image-caption url="[types field='my-gallery' output='raw'][/types]"]
    </div>
  </div>
[/wpv-for-each]


You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/displaying-caption-from-media-post/

Leave a Reply

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