【WordPress】アイキャッチ画像を挿入しよう
はじめに
自分のテンプレートをゼロから作った場合、投稿するときにアイキャッチ画像が挿入できない。そこで、今回はアイキャッチ画像を挿入できるようプログラムを書き換えよう。
手順
-
functions.php
を作成する。(function.php
にしないように)
functions.php
<?php
add_action('init', function(){
add_theme_support('post-thumbnails');
});
functions.php
を作成する。(function.php
にしないように)<?php
add_action('init', function(){
add_theme_support('post-thumbnails');
});
phpの閉じタグが最後に来る場合、?>
を省略することが可能。
- 投稿にアイキャッチ画像を表示させる
<?php the_post_thumbnail(); ?>
<?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)); ?>
と引数を入れれば良い。
<?php
$id = get_post_thumbnail_id();
var_dump($id); // 追記
$img = wp_get_attachment_image_src($id);
?>
上のコードの場合、
というふうに、WordPress上にサムネイルのIDを表示させることができる。
- 画質の調整
画質を調節したい場合は、
$img = wp_get_attachment_image_src($id, 'large');
と第二引数を変えてあげれば良い。
- デフォルト画像を設ける
デフォルト画像を設定したい場合は、
<?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;
?>
と記述すれば良い。
劇的に画質が良くなっていることがわかるだろう。
関数
再利用する場合は、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;
}
終わりに
自作テンプレートにはデフォルトでアイキャッチ画像を設定する項目がない。そのため、アイキャッチ画像を設定するコードを書き加えれば良い。
Author And Source
この問題について(【WordPress】アイキャッチ画像を挿入しよう), 我々は、より多くの情報をここで見つけました https://qiita.com/eee-lin/items/855d3193619c6633dffe著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .