CHIPS

制作チップス

アイキャッチ画像の出力タグ「the_post_thumbnail」 に alt 属性をつける

2025年6月20日

カテゴリー: 制作チップス

アイキャッチ画像の出力タグ「the_post_thumbnail」に alt 属性をつけるには、get_the_post_thumbnail() を使ってHTMLをカスタマイズするのがベストです。

get_the_post_thumbnail() + get_the_title() を使う

<?php
$thumbnail_id = get_post_thumbnail_id();
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
if (!$alt) {
  $alt = get_the_title(); // 代替テキストが未設定ならタイトルを代用
}
echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array('alt' => esc_attr($alt)));
?>

別の画像サイズ(medium, large など)を使いたい場合は、 'thumbnail' を置き換える。

もっとシンプルにタイトルを使う

<?php
echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array('alt' => esc_attr(get_the_title())));
?>

実用例

メディアライブラリ内で「代替テキスト」が未設定の場合、get_the_title() を代用する。

<div class="blog-box">
<?php
  $args = array(
  'post_type' => 'post',
	'posts_per_page' => 1, // 表示件数の指定
	 'cat' => '4'
  );
  $the_query = new WP_Query($args); if($the_query->have_posts()):
?>
<?php while ($the_query->have_posts()): $the_query->the_post(); ?>
	<dl>   
	<dt><a href="<?php the_permalink(); ?>">
	<?php
if (has_post_thumbnail()) :
    $thumbnail_id = get_post_thumbnail_id(); // 画像ID取得
    $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); // alt取得

    // altが空なら記事タイトルを代わりに使う
    if (empty($alt)) {
        $alt = get_the_title();
    }

    echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array(
        'alt' => esc_attr($alt)
    ));
else :
?>
    // サムネイルがなかったら代替え画像を使う
    <img src="<?php echo esc_url(first_catch_image()); ?>" alt="<?php echo esc_attr(get_the_title()); ?>">
<?php endif; ?>
	</a></dt>
	<dd><p class="day"><?php the_time('Y/n/j'); ?></p>
	<h4><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h4>
	<?php
	add_filter( 'excerpt_length', function ( $length ) {
	return 40;
	}, 999 );
	the_excerpt();
	?>
	</dd>
	</dl> 
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>

アイキャッチ画像がない場合、投稿記事の最初の画像を代替えで表示する方法はこちら

SVG画像の代替テキストの設定はこちら