Wordpress - How to get image title/alt attribute?
Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.
// An attachment/image ID is all that's needed to retrieve its alt and title attributes.
$image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.
$size = 'my-size' // Defaults to 'thumbnail' if omitted.
$image_src = wp_get_attachment_image_src($image_id, $size)[0];
Your problem is that you are not providing the correct attachment's ID to get_post_meta()
and get_the_title()
functions.
This is your code to get the alt
of the image:
$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
And it is correct, but $attachment->ID
is not defined in your code, so, the function does not return anything.
Reading your code, it seems that you store the ID of the image as a meta field and then you get it with this code:
$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);
So, assuming that $image->id
is correct in your code, you should replace this:
$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
With:
$image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);
That is for getting the alt
, to get the title:
$image_title = get_the_title( $image->id );
I use a quick function in all my themes to get image attachment data:
//get attachment meta
if ( !function_exists('wp_get_attachment') ) {
function wp_get_attachment( $attachment_id )
{
$attachment = get_post( $attachment_id );
return array(
'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink( $attachment->ID ),
'src' => $attachment->guid,
'title' => $attachment->post_title
);
}
}
Hope this helps!