好哇网

WordPress缩略图调用输出alt以及title信息 Post thumbnail alt title

作者 2021-06-5 985

WordPress可以很方便的调用缩略图,如果你想在缩略图使用过程中输出alt以及title信息,基本上有两种思路:

  1. 获取,缩略图的id,然后调用指定尺寸的图像地址,在输出的时候添加alt以及title
  2. 通过wp的内置函数添加一些额外信息

通常我们输出缩略图的代码如下:

1
the_post_thumbnail('news');

其中news为缩略图的尺寸名称。如果我们想要添加alt以及title需要怎么做呢?

1
2
3
4
5
$post_thumbnail_attr = array(
    'alt'   => get_the_title(),
    'title' => get_the_title(),
);
the_post_thumbnail('news', $post_thumbnail_attr);

刷新一下看一下吧,你已经成功了

在国外网站上找到一些解决方案:

1
2
3
4
5
6
<?php if ( has_post_thumbnail() ) :?>
            <a href="<?php the_permalink() ?>" class="thumb"><?php the_post_thumbnail('thumbnail', array(
                        'alt'	=> trim(strip_tags( $post->post_title )),
                        'title'	=> trim(strip_tags( $post->post_title )),
                    )); ?></a>
            <?php endif; ?>

You have two options. Either use the featured image’s caption (which can some times be blank) or use the post’s title as alt.

You can get the caption by using get_post_meta(). Using it is as simple as this:

1
2
$alt = get_post_meta ( $image_id, '_wp_attachment_image_alt', true );
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE" />';

It should be used in the loop though, or be passed the $post object or ID.

The alternative method is to use post’s title as alt text. To do so, you can use:

1
echo '<img alt="' . esc_html ( get_the_title() ) . '" src="URL HERE" />';

You can set up a conditional and check if the thumbnail has a caption, and use it instead of post title, if available:

1
2
3
4
5
6
7
if ( $alt = get_the_post_thumbnail_caption() ) {
    // Nothing to do here
} else {
    $alt = get_the_title();
}
 
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE"/>

UPDATE

If you wish to add the alt attribute directly to get_post_thumbnail(), you can pass it as an array to the function:

1
the_post_thumbnail( 'thumbnail', [ 'alt' => esc_html ( get_the_title() ) ] );

最后一种方法貌似简单很多,直接传入参数就行了!

发表评论

好哇网,每天提供1000+次下载,做你身边靠谱的下载站!

立刻探索下载

留言咨询