WordPress - 投稿一覧ページにアイキャッチ画像を追加する
1. アイキャッチ画像の機能を有効化する
投稿の編集画面でアイキャッチ画像を追加できるようにするために下記を記述します。
//functions.php
//アイキャッチ画像有効化
add_theme_support( 'post-thumbnails' );
2. アイキャッチ画像(サムネイル)のサイズを設定する
アイキャッチ画像を呼び出すときに画像サイズ($size)を指定することがあるので、「管理画面 > 設定 > メディア」 からアイキャッチ画像(サムネイル)の画像サイズを設定します。サムネイルとアイキャッチ画像は呼び名が変更されましたが同じものです。
メディア設定 | デフォルトサイズ | $size |
---|---|---|
サムネイルのサイズ | 150 x 150 | thumbnail |
中サイズ | 300 x 300(上限) | medium |
画像の元のサイズ | - | full |
3. アイキャッチ画像を表示する
アイキャッチ画像を表示させたいところに下記を記述します。
<?php if ( has_post_thumbnail() ): ?>
<?php the_post_thumbnail(); ?>
<?php endif; ?>
<!-- [HTML出力]
<img width="xxx" height="xxx" src="http://xxx.png"
class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" />
-->
<?php if ( has_post_thumbnail() ): ?> ~ <?php endif; ?>
投稿にアイキャッチ画像が設定されているか調べる
<?php the_post_thumbnail( $size, $attr ); ?>
アイキャッチ画像を表示する
画像サイズや class を出力したくない場合
<?php if ( has_post_thumbnail() ): ?>
<?php $post_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail');?>
<img src="<?php echo $post_thumb[0]; ?>">
<?php endif; ?>
<!-- [HTML出力]
<img src="http://xxx.png">
-->
<?php wp_get_attachment_image_src( $attachment_id, $size, $icon ); ?>
画像ファイルの"url"、"width"、"height"属性を配列として返す
<?php $post_thumbnail_id = get_post_thumbnail_id( $post_id ); ?>
アイキャッチ画像の ID を返す
関数リファレンス/wp get attachment image src
テンプレートタグ/get post thumbnail id
アイキャッチ画像がない場合、替わりの画像を表示する
投稿にアイキャッチ画像を設定していない場合に替わりの画像を表示する場合は下記のように記述します。ここではアイキャッチ画像がない場合、「images ファルダ」の「xxx.png」という画像を表示するようにしています。
<?php if ( has_post_thumbnail() ): ?>
<?php $post_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail');?>
<img src="<?php echo $post_thumb[0]; ?>">
<?php else: ?>
<img src="<?php echo get_template_directory_uri(); ?>/images/xxx.png" >
<?php endif; ?>
<?php echo get_template_directory_uri(); ?>
ディレクトリの URI を取得
関数リファレンス/get template directory uri
4. 関数化してアイキャッチ画像を呼び出しやすくする
//functions.php
//アイキャッチ画像関数化
function cs_thumb( $size = 'thumbnail' ) {
if( has_post_thumbnail()) {
$post_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), $size );
$url = $post_thumb[0];
} else {
$url = get_template_directory_uri() . '/images/xxx.png';
}
return $url;
}
アイキャッチ画像を表示させたいところに下記を記述します。
<img src="<?php echo cs_thumb(); ?>" alt="">