この技術ブログは、自分の備忘録も兼ねている。
できるだけ時間をかけずに記録をしていきたい。
毎回の投稿のたびに、アイキャッチ画像を作成し、設定するのは少し手間。
そこでカテゴリーごとにアイキャッチ画像を自動で設定されるようにした。

SWELLは、カテゴリーページで、カテゴリーのアイキャッチ画像を設定することができる。今後変更することも考えて、この画像を使う。
目次
コード
以下のコードを子テーマのfunctions.phpに追加する。
function default_category_eyecatch() {
global $post;
if ( ! isset($post) || ! is_a($post, 'WP_Post') ) return;
// すでにアイキャッチがある場合は何もしない
if ( has_post_thumbnail($post->ID) )
return;
// ① 本文に含まれる添付画像を取得
$preset_image = get_children([
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
]);
if ( $preset_image ) {
foreach ( $preset_image as $attachment_id => $attachment ) {
set_post_thumbnail( $post->ID, $attachment_id );
return;
}
}
// ② カテゴリ画像(SWELLの設定)を取得
$categories = get_the_category( $post->ID );
if ( ! empty( $categories ) ) {
foreach ( $categories as $cat ) {
$cat_thumb_id = get_term_meta( $cat->term_id, 'swell_term_meta_image', true );
if ( $cat_thumb_id ) {
set_post_thumbnail( $post->ID, (int)$cat_thumb_id );
return;
}
}
}
}
add_action( 'the_post', 'default_category_eyecatch' );
この機能の特徴として、記事を開いたとき、投稿にアイキャッチがなければ、新しくアイキャッチ画像が保存(設定)される。
set_post_thumbnail( $post->ID, $画像ID );
投稿データに「アイキャッチ画像としてこの画像を登録」する処理
アイキャッチが設定される順番
- すでに投稿に設定されているアイキャッチ画像
- 記事内で最初につかっている画像
- カテゴリーのアイキャッチ画像
※カテゴリの画像も設定されていない場合は何もしない(SWELLの外観>カスタマイズで設定していたデフォルト画像が表示される。)
※画像IDはメディアライブラリで画像を選択するとURLにでてくる。
