I am trying to get metadata associated with the featured image but get_post_meta
keeps returning empty.
$image_alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);
This works and returns the data, but the code below does not work:
$image_description = get_post_meta($image_id, '_wp_attachment_description', true);
$image_caption = get_post_meta($image_id, '_wp_attachment_caption', true);
These two return empty. I filled out those fields but I can not get them back in my template!
I am trying to use Alt Text
, Title
, Caption
and Description
of the featured image to improve my website SEO, but I can not figure out why they’re coming out empty.
I found this post and this post, but they make me even more confused.
Would you please help me?
Thank you in advance.
2
Answers
The Caption is actually the
POST Excerpt
and the Description is actually thePOST Content
So you would do this:
Because in the post meta table there is no key called
'_wp_attachment_description'
. Same thing with'_wp_attachment_caption'
. They’re stored in the posts table. That’s whyget_post_meta
returns empty!First way
So let’s say,for example, I upload one of the wordpress’s logo and populate those metadata fields, like this:
Now in order to get the data you’re looking for you could use
attachment_url_to_postid
andget_post_field
functions. So you could do something like this:In order to test it, we could do something like this:
Which outputs this:
NOTE:
post_content
and image caption is stored aspost_excerpt
.post_type
andmime_type
for you!Second way, in the wordpress loop
If you want to get the metadata in the wordpress loop, we could use
get_post_thumbnail_id
function. So you could use the following code:Which outputs this:
Third way, refactoring and optimizing our code a little bit!
In both solutions above, we’re repeating ourselves. So to follow "DRY" principle, we could write a reusable function which will return an associative array of the metadata related to an image id. Like so:
This function goes into the
functions.php
file of your theme.Now in order to use this function in your templates, you could do something like this:
Or in the wordpress loop:
Which outputs this associative array:
Hope this answer clears things up for you!
This answer has been fully tested on wordpress
5.8
and works fine!