admin管理员组

文章数量:1122832

Isn't get_the_post_thumbnail() supposed to output the alt and title attributes according to what is set for the image in the Media Library? When using get_the_post_thumbnail() in Wordpress 6.6, no alt or title attributes are output. I have to do something like the following to load them manually:

$post_thumbnail_id = get_post_thumbnail_id($post);
$alt = get_post_meta($post_thumbnail_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($post_thumbnail_id);
$post_thumbnail = get_the_post_thumbnail($post, 'full', ['alt' => $alt, 'title' => $image_title]);

Isn't get_the_post_thumbnail() supposed to output the alt and title attributes according to what is set for the image in the Media Library? When using get_the_post_thumbnail() in Wordpress 6.6, no alt or title attributes are output. I have to do something like the following to load them manually:

$post_thumbnail_id = get_post_thumbnail_id($post);
$alt = get_post_meta($post_thumbnail_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($post_thumbnail_id);
$post_thumbnail = get_the_post_thumbnail($post, 'full', ['alt' => $alt, 'title' => $image_title]);
Share Improve this question asked Sep 14, 2024 at 5:08 arrr_mateyarrr_matey 11 bronze badge 2
  • 1 wordpress.stackexchange.com/questions/357463/… – BlueDogRanch Commented Sep 14, 2024 at 21:38
  • 1 thank you and I saw that post. I have no custom filters running as that poster did – arrr_matey Commented Sep 15, 2024 at 8:44
Add a comment  | 

1 Answer 1

Reset to default 0

The $attr argument to get_the_post_thumbnail() is optional, so the default value is an empty string. If it's called with no $attr argument, it passes the same empty string through to wp_get_attachment_image(), which returns the markup for an <img> element with an empty alt attribute. This is default behaviour.

If you wanted to override this behaviour for all images, it would just be a matter of adding a filter on wp_get_attachment_image_attributes:

 function wpse426788_add_alt_text( $attr, $attachment ) {
 
    $newatts['alt'] = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', TRUE );
    
    $attr = array_merge( $attr, $newatts );
    
    return $attr;
 }
 
 add_filter( 'wp_get_attachment_image_attributes', 'wpse426788_add_alt_text', 10, 2 );

本文标签: post thumbnailsgetthepostthumbnail() alt and title attributes missing