2
$output .= '
    <img 
        class="class1" 
        src="'.$atts['to'].'" 
        alt="The First Caption" 
        width="100%" 
        height="auto"
    >';

Instead of first caption, I want to fetch the caption/description of the image.

can some one guide me how to do this?

I tried this → wp_get_attachment_caption but it didn't work.

1 Answer 1

2

You can directly get an attachment's meta data if you have it's ID. The alt data for an attachment is stored in _wp_attachment_image_alt.

So, you can use:

$alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);

To get the caption of an image, you can use wp_get_attachment_metadata().

$metadata = wp_get_attachment_metadata( $id );
$caption = $metadata['image_meta']['caption'];

EDIT

Based on the code in your comment, this is the full shortcode's code:

function simplisto_the_image($atts) {
    $atts = shortcode_atts(
        array( 
            'to' => 'http://example.com/image.jpg' 
        ), 
        $atts
    );
    $caption = '';
    // Get the attachment's ID from its URL, if the URL is valid
    $url = filter_var( $atts['to'], FILTER_SANITIZE_URL);
    if( filter_var( $url, FILTER_VALIDATE_URL) ) {
        $attachment_id = attachment_url_to_postid( $url );
        // Get the attachment's alt, if its a valid ID
        if( $attachment_id ){
            $caption = wp_get_attachment_caption( $attachment_id );
        }
    }

    $output = '<div class="lazyimg">'; 
    $output .= '<img class="lazyimg-popup" src="'.$atts['to'].'" alt="' .$caption. '" width="100%" height="auto">'; 
    $output .= '<i class="fa fa-expand" aria-hidden="true"></i>'; 
    $output .= '</div>'; 
    return $output; 
}
add_shortcode('simage', 'simplisto_the_image');

The shortcode will accept an image URL and fetch it's metadata, if it's valid.

4
  • sir, do we have the correct title or should we change this so that right people may find this in future?
    – WordCent
    Aug 11, 2017 at 10:29
  • Hi. The caption of an image is used for inline images, such as those description under the image in posts. But the alt attribute is used for search engines or when an image can not be loaded, so that the text is shown instead of the image. So, the correct way is to use alt for alt, and caption for description in posts.
    – Johansson
    Aug 11, 2017 at 10:44
  • 1
    Do you mean the title of the post? or your function? Since your question's title is correct.
    – Johansson
    Aug 11, 2017 at 10:46
  • Yes, I mean the post title.
    – WordCent
    Aug 11, 2017 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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