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.