我想使用代码<img class="img-responsive" src="<?php echo the_post_thumbnail_url(); ?>" alt="" />
而不是<?php the_post_thumbnail(); ?>
, 输出帖子缩略图。现在,如何动态获取文章缩略图的“alt”和“title”。wordpress是否为此提供了任何功能。我在wordpress codex/开发者网站上寻找了一个函数来解决这个问题,但没有找到。
如何为WordPress代码在图片中写“alt”标签?
1 个回复
最合适的回答,由SO网友:cjbj 整理而成
你为什么要避免the_postthumbnail
? 如果使用正确的属性,它可以为您提供所需的确切html。无论如何,您可以访问图像的标题和alt标记,如下所示:
// get the ID of the featured image
$thumbnail_id = get_post_thumbnail_id( $post_id );
// retrieve title (an image is a post, so you can access the title as if it is a post title)
$title = get_post($thumbnail_id())->post_title;
// retrieve alt (which is stored as metadata to a post)
$alt = get_post_meta($thumbnail_id, \'_wp_attachment_image_alt\', true);