We often upload images to wordpress site as attachments, we can add caption, description, alt text for it. In this tutorial, we will introduce how to get its caption, description, alt text, size and url information.
Preliminary
We know the id of image attachment is 50.
$attachment_id = 50
Get image attachment alt text
$alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true ); echo $alt;
Get image attachment title
$title = get_the_title($attachment_id); print_r($title);
The title is: Creating a Custom Scrollbar Using Scrollbot with Custom Style
Get image attachment caption
$caption = get_the_excerpt($attachment_id); print_r($caption); $caption = wp_get_attachment_caption($attachment_id); print_r($caption);
We can use get_the_excerpt() and wp_get_attachment_caption() to get image caption.
It is: Image caption test
Get image attachment description
$desc = get_the_content($attachment_id); print_r($desc);
or
$img = get_post($attachment_id); print_r($img->post_content);
The description is: Image description test
Get image attachment url
$url = wp_get_attachment_url($attachment_id); echo $url;
Get image attachment size
$meta = wp_get_attachment_metadata($attachment_id); print_r($meta);
The result is:
Array ( [width] => 560 [height] => 350 [file] => 2020/04/Creating-a-Custom-Scrollbar-Using-Scrollbot-with-Custom-Style.png [sizes] => Array ( [thumbnail] => Array ( [file] => Creating-a-Custom-Scrollbar-Using-Scrollbot-with-Custom-Style-150x150.png [width] => 150 [height] => 150 [mime-type] => image/png ) [medium] => Array ( [file] => Creating-a-Custom-Scrollbar-Using-Scrollbot-with-Custom-Style-300x188.png [width] => 300 [height] => 188 [mime-type] => image/png ) [tab-small] => Array ( [file] => Creating-a-Custom-Scrollbar-Using-Scrollbot-with-Custom-Style-60x60.png [width] => 60 [height] => 60 [mime-type] => image/png ) ) [image_meta] => Array ( [aperture] => 0 [credit] => [camera] => => [created_timestamp] => 0 [copyright] => [focal_length] => 0 [iso] => 0 [shutter_speed] => 0 [title] => [orientation] => 0 [keywords] => Array ( ) ) )
The width and height are: $meta[‘width’] and $meta[‘height’]