Output title, caption, description or alt attribute of image fields (or file fields)

/**
 * Register shortcode 'media-field'
 * 
 * Pass URL of media as shortcode content
 * Attribute 'output' specifies what to return, defaults to media title
 * 
 * example usage:
 * [media-field output='alt'][/media-field]
 */
add_shortcode('media-field', function ($atts = [], $content = null) {

	// provide default
	$atts = shortcode_atts(
		array(
			'output' => 'title',
		),
		$atts
	);

	$output = '';

    if (isset($content)) {
        $url = do_shortcode( $content );

        // get the ID of the media post for the URL contained in content
        $media_id = attachment_url_to_postid($url);

        $media = get_post($media_id);

        switch ($atts['output']) {
            case 'title':
                $output = $media->post_title;
                break;
            case 'caption':
                $output = $media->post_excerpt;
                break;
            case 'description':
                $output = $media->post_content;
                break;
            case 'alt':
                $output = get_post_meta( $media_id, '_wp_attachment_image_alt', true );
                break;
        }
	}
	return $output;
});

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Beda Schmid
5 years ago

Cool

Note, Image Caption is the posts the_excerpt, the Image Description is the_content, and Image Title is the_title.
So you can use Toolset ShortCodes as well (if you have the Image ID)
You can get ID from URL too (attachment_url_to_postid($url), not with Toolset)

Can help as well to display those 😉