1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【WordPress】アイキャッチ画像を挿入しよう

Last updated at Posted at 2021-02-05

はじめに

自分のテンプレートをゼロから作った場合、投稿するときにアイキャッチ画像が挿入できない。そこで、今回はアイキャッチ画像を挿入できるようプログラムを書き換えよう。

手順

  • functions.phpを作成する。(function.phpにしないように)
functions.php
<?php
add_action('init', function(){
  add_theme_support('post-thumbnails');
});

phpの閉じタグが最後に来る場合、?>を省略することが可能。

  • 投稿にアイキャッチ画像を表示させる

<?php the_post_thumbnail(); ?>

single.php
  <?php
  $id = get_post_thumbnail_id();
  $img = wp_get_attachment_image_src($id);
  ?>
  <header class="masthead" style="background-image: url('<?php echo $img[0]; ?>')">

サムネイルを表示させるには、
<?php the_post_thumbnail(); ?>
という一文を書き加えれば良い。

  • 画像のサイズを変更

画像のサイズを調整したい場合は、
<?php the_post_thumbnail(array(32,32)); ?>
と引数を入れれば良い。

single.php
  <?php
  $id = get_post_thumbnail_id();
  var_dump($id); // 追記
  $img = wp_get_attachment_image_src($id);
  ?>

上のコードの場合、

スクリーンショット 2021-02-05 4.54.10.png

というふうに、WordPress上にサムネイルのIDを表示させることができる。

  • 画質の調整

画質を調節したい場合は、
$img = wp_get_attachment_image_src($id, 'large');
と第二引数を変えてあげれば良い。

  • デフォルト画像を設ける

デフォルト画像を設定したい場合は、

single.php
  <?php
  if (has_post_thumbnail()):
    $id = get_post_thumbnail_id();
    $img = wp_get_attachment_image_src($id, 'large');
  else:
    $img = array(get_template_directory_uri().'/img/post-bg.jpg');
  endif;
  ?>

と記述すれば良い。

実際にどう変わるか確認してみると、
スクリーンショット 2021-02-05 5.03.39.png

劇的に画質が良くなっていることがわかるだろう。

関数

再利用する場合は、functions.phpに関数としてまとめておくことも可能だ。

functions.php
<?php
add_action('init', function(){
  add_theme_support('post-thumbnails');
});

/* アイキャッチ画像がなければ、標準画像を取得する */
function get_eyecatch_with_default() {
  if (has_post_thumbnail()):
    $id = get_post_thumbnail_id();
    $img = wp_get_attachment_image_src($id, 'large');
  else:
    $img = array(get_template_directory_uri().'/img/post-bg.jpg');
  endif;

  return $img;
}

終わりに

自作テンプレートにはデフォルトでアイキャッチ画像を設定する項目がない。そのため、アイキャッチ画像を設定するコードを書き加えれば良い。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?