WordPressのカテゴリーにフォールバック機能付き画像を設定することは、特にコンテンツ量の多いブログにとっては、非常に時間の節約になることがわかりました。
特集画像がない記事がある場合、またはカテゴリー内のすべての記事に同じようなサムネイルを表示させたい場合は、カテゴリーごとにフォールバック画像を設定できます。
こうすることで、フィーチャー画像のないブログ記事はなくなるし、すべての記事に手動で画像を割り当てる必要もなくなる。
この投稿では、WordPressで特定のカテゴリーに初期設定のフォールバックアイキャッチ画像を設定する方法を紹介します。

なぜ投稿カテゴリーにフォールバックアイキャッチ画像を追加するのか?
WordPressブログで、各投稿に個別カテゴリーを割り当てているとします。そのカテゴリー内のすべての投稿に、何らかの理由でアイキャッチ画像がない場合に同じフォールバック画像を表示するように割り当てることができます。
投稿カテゴリーにフォールバック画像を追加するもう一つの利点は、カテゴリーアーカイブページが多くの検索トラフィックを獲得している場合、そのページをより魅力的で魅力的にすることです。
とはいえ、WordPressプラグインとカスタムコードを使って、投稿カテゴリーに基づいたフォールバック画像を追加する方法を見てみましょう。
WordPressでプラグインを使用してフォールバックアイキャッチ画像を設定する
WordPressの初期設定では、投稿カテゴリーページに画像を追加するオプションはありません。しかし、WordPressプラグインを使えば、投稿カテゴリーにフォールバック画像を簡単に設定することができます。
まず、カテゴリーとタクソノミーのイメージプラグインをインストールし、有効化する必要があります。詳しくはWordPressプラグインのインストール方法をご覧ください。
有効化した後、WordPressの管理画面から設定 ” タクソノミー画像に向かうことができます。次の投稿では、’カテゴリー’チェックボックスをクリックして、タクソノミー画像を投稿カテゴリーに含めることができます。

完了したら「変更を保存」ボタンをクリックするのをお忘れなく。
その後、WordPressダッシュボードから投稿 ” カテゴリーに移動できます。新しいカテゴリーを追加したり、既存のカテゴリーを編集したりすると、「外観」フィールドが表示されます。

WordPressのカテゴリーに追加したい画像のURLを入力するだけです。詳しくは、WordPressでアップロードした画像のURLを取得する方法をご覧ください。
これで、アイキャッチ画像が割り当てられていないブログ投稿を公開すると、WordPressはカテゴリーに設定した画像を使用します。
デモサイトで使用した画像のプレビューです。
これですべてです!これで投稿カテゴリーに基づいたフォールバック画像の追加に成功しました。
WordPressでプラグインなしでフォールバックアイキャッチ画像を設定する
WordPressプラグインを使わなくても、投稿カテゴリーのフォールバック画像を設定することもできる。ただし、この方法はコードスニペットを含むため、初心者にはお勧めできない。
まず最初に、WordPressカテゴリー用の画像を作成する必要があります。カテゴリースラッグを画像ファイル名として使用し、JPGやPNGなどすべて同じ形式で保存します。
次に、メディア ” 新規追加からカテゴリー画像をWordPressサイトにアップロードします。

WordPressはアップロード中にカテゴリー画像を保存し、テーマによって定義された画像サイズを作成します。
カテゴリー画像をアップロードしたら、別のディレクトリに移動する必要があります。FTPクライアントを使用してサイトに接続し、/wp-content/uploads/
フォルダに移動します。

アップロードしたカテゴリー画像は、/uploads/2022/08/の
ように月のフォルダーに保存されます。
今月のフォルダーを開いてください。

詳しくは、WordPressで画像をサイトに保存する方法についてをご覧ください。
次に、コンピューターのデスクトップにフォルダーを作成し、category-imagesと名付けます。ここで、すべてのカテゴリー画像とWordPressで作成したすべてのサイズをデスクトップのこの新しいフォルダにダウンロードします。
ダウンロードが完了したら、category-images フォルダーを /wp-content/uploads ディレクトリにアップロードする必要があります。こうすることで、すべてのカテゴリー画像サイズを区切りのよいフォルダーに収めることができ、テーマに簡単に呼び出すことができるようになります。
詳しくは、FTPを使ってWordPressにファイルをアップロードする方法をご覧ください。
カテゴリー画像を初期設定のアイキャッチ画像として表示する。
次の投稿では、カテゴリー内の投稿にアイキャッチ画像が設定されていない場合に、これらの画像の1つを予備のアイキャッチ画像として表示する方法を紹介します。
この方法はコピー&ペーストを伴いますので、通常ユーザーにはテーマファイルの編集をお勧めしません。小さなミスがサイトに大きなエラーを引き起こす可能性があります。
サイトにコードを追加する簡単な方法は、WPCodeを使用することです。これは最高のWordPressコードスニペットプラグインで、サイト上のカスタムコードを安全かつ簡単に管理することができます。
まず、無料のWPCodeプラグインをインストールし、有効化する必要があります。詳しくは、WordPressプラグインのインストール方法をご覧ください。
次に、WordPress管理画面の「Code Snippets ” + Add Snippet」で新しいスニペットを追加します。そして、「新規追加」ボタンをクリックします。

その後、カスタムコードを追加するか、WPCodeライブラリからスニペットを使用することができます。
カスタムコードの追加(新規スニペット)」オプションにマウスオーバーし、「スニペットを使用」オプションをクリックしてください。

次に、画面に表示されるオプションのリストから、コードタイプとして「PHP Snippet」を選択する必要がある。

スニペットの名前を追加してください。これは、何のコードかを覚えておくのに役立つものであれば何でもかまいません。

その後、以下のコード・スニペットをコピー&ペーストして、「コード・プレビュー」フィールドに入力するだけです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | /** * Plugin Name: Category Thumbnail Fallback * Description: Use the category image as fallback when the post does not have a featured image */ class WPBCategoryThumbnailFallback { protected static $taxonomies = [ 'category' ]; protected $nonceId = 'wpb_category_thumb_fallback_none' ; protected $fieldId = 'wpb_category_fallback_post_image' ; public $taxonomy ; protected function __construct( $taxonomy ) { $this ->taxonomy = $taxonomy ; } public static function init() { foreach ( static :: $taxonomies as $taxonomy ) { $_self = new self( $taxonomy ); add_action( 'admin_enqueue_scripts' , [ $_self , 'scripts' ]); add_action( "{$taxonomy}_add_form_fields" , [ $_self , 'add' ]); add_action( "{$taxonomy}_edit_form_fields" , [ $_self , 'edit' ], 99, 2); add_action( "created_{$taxonomy}" , [ $_self , 'saveTerm' ], 10, 2); add_action( "edited_{$taxonomy}" , [ $_self , 'editTerm' ], 10, 2); add_filter( "get_post_metadata" , [ $_self , 'fallback' ], 99, 5); } } public function scripts( $hook_suffix ) { if (in_array( $hook_suffix , [ 'term.php' , 'edit-tags.php' ])) { $screen = get_current_screen(); if ( is_object ( $screen ) && "edit-{$this->taxonomy}" == $screen ->id) { wp_enqueue_media(); wp_add_inline_script( 'media-editor' , $this ->inlineScript()); } } } public function add() { ?> <div class = "form-field upload_image-wrap" > <label for = "upload_image" >Image</label> <input id= "upload_image" type= "hidden" size= "36" name="<?php echo esc_attr( $this ->fieldId) ?> " value=" "/> <div id= "wpb-category-image-preview" style= "max-width: 150px; max-height: 150px;" ></div> <input id= "upload_image_button" class = "button" type= "button" value= "Upload Image" /> <p>Enter a URL or upload an image</p> </div> <?php wp_nonce_field( $this ->nonceId, $this ->nonceId); } public function edit( $term , $taxonomy ) { $value = get_term_meta( $term ->term_id, $this ->fieldId, true); $image = wp_get_attachment_image((int) $value ); ?> <tr class = "form-field upload_image-wrap" > <th scope= "row" ><label for = "name" >Image</label></th> <td> <label for = "upload_image" > <input id= "upload_image" type= "hidden" size= "36" name="<?php echo esc_attr( $this ->fieldId) ?> " value=" <?php echo esc_attr( $value ) ?>"/> <div id= "wpb-category-image-preview" style= "max-width: 150px; max-height: 150px;" ><?php echo $image ; ?></div> <input id= "upload_image_button" class = "button" type= "button" value= "Upload Image" /> </label> <p class = "description" >Enter a URL or upload an image</p> </td> </tr> <?php wp_nonce_field( $this ->nonceId, $this ->nonceId); } public function saveTerm( $term_id , $tt_id ) { $data = array_filter (wp_unslash( $_POST ), function ( $value , $key ) { return in_array( $key , [ $this ->nonceId, $this ->fieldId]); }, ARRAY_FILTER_USE_BOTH); if ( empty ( $data ) || empty ( $data [ $this ->nonceId]) || ! wp_verify_nonce( $data [ $this ->nonceId], $this ->nonceId) || ! current_user_can( 'manage_categories' ) ) { return null; } if ( empty ( $data [ $this ->fieldId]) || empty (absint( $data [ $this ->fieldId]))) { return delete_term_meta( $term_id , $this ->fieldId); } $value = absint( $data [ $this ->fieldId]); return update_term_meta( $term_id , $this ->fieldId, $value ); } public function editTerm( $term_id , $tt_id ) { $this ->saveTerm( $term_id , $tt_id ); } public function fallback( $null , $object_id , $meta_key , $single , $meta_type ) { if ( $null === null && $meta_key === '_thumbnail_id' ) { $meta_cache = wp_cache_get( $object_id , $meta_type . '_meta' ); if ( ! $meta_cache ) { $meta_cache = update_meta_cache( $meta_type , [ $object_id ]); $meta_cache = $meta_cache [ $object_id ] ?? null; } $val = null; if (isset( $meta_cache [ $meta_key ])) { if ( $single ) { $val = maybe_unserialize( $meta_cache [ $meta_key ][0]); } else { $val = array_map ( 'maybe_unserialize' , $meta_cache [ $meta_key ]); } } if ( empty ( $val )) { $fallbackImageId = $this ->getPostFallbackImageId( $object_id , $single ); if ( ! empty ( $fallbackImageId )) { return $fallbackImageId ; } } return $val ; } return $null ; } public function getPostFallbackImageId( $postId , $single ) { $terms = get_the_terms( $postId , $this ->taxonomy); if ( empty ( $terms ) || is_wp_error( $terms )) { return null; } foreach ( $terms as $term ) { $fallbackIdFromCategoryId = get_term_meta( $term ->term_id, $this ->fieldId, $single ); if ( ! empty ( $fallbackIdFromCategoryId )) { return $fallbackIdFromCategoryId ; } } return null; } public function inlineScript() { return "jQuery(document).ready( function ($) { var custom_uploader; $( '#upload_image_button' ).click( function (e) { e.preventDefault(); //If the uploader object has already been created, reopen the dialog if (custom_uploader) { custom_uploader.open(); return ; } //Extend the wp.media object custom_uploader = wp.media.frames.file_frame = wp.media({ title: 'Choose Image' , button: { text: 'Choose Image' }, multiple: true }); //When a file is selected, grab the URL and set it as the text field's value custom_uploader.on( 'select' , function () { console.log(custom_uploader.state().get( 'selection' ).toJSON()); attachment = custom_uploader.state().get( 'selection' ).first().toJSON(); var thumbUrl = attachment && attachment.sizes && attachment.sizes.thumbnail && attachment.sizes.thumbnail.url ? attachment.sizes.thumbnail.url : attachment.url; $( '#wpb-category-image-preview' ).html( '<img src=\"' + thumbUrl + '\">' ); $( '#upload_image' ).val(attachment.id); }); //Open the uploader dialog custom_uploader.open(); }); });"; } } |
次に、’インサーター’セクションまでスクロールダウンし、’Auto Insert’を選択すると、プラグインがあなたの代わりに配置を処理します。
次に、「場所」ドロップダウンメニューの「ページ、投稿、カスタム投稿タイプ」セクションで「コンテンツの前に挿入」オプションを選択します。

その後、ページのトップに戻り、トグルを「非活性化」から「有効化」に切り替えることができる。
上部にある「スニペットを保存」ボタンをクリックすると、フォールバック画像が配置されます。

WordPressでカスタムコードスニペットを追加する方法については、こちらのガイドもご参照ください。
注:このコード・スニペットは’カテゴリー’タクソノミーのみで動作します。しかし、コード内の以下のクラスのリストにそれらの名前を追加し、括弧で囲まれたキーワードを’タグ’や’投稿’などに変更することで、より多くのタクソノミーを追加することができます。
1 | protected static $taxonomies = [ 'category' ]; |
完了したら、あなたのサイトにアクセスして、フォールバック画像を見るだけです。
この記事が、投稿カテゴリーに基づいたフォールバック画像を追加するのにお役に立てば幸いです。また、WordPressの投稿にプログレスバーを追加する方法や、ウェブサイトグラフィックに最適なCanvaの代用品もご紹介しています。
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Nicola
Most interesting would to have a hook to replace thumbnail to be used in functions so not to bother replacing wherever the thumbnail is used
Sohail
Thank you. This works like a charm
While the fallback featured image gets displayed in the post; any ideas on how could I display them in category/archive pages, or where the posts get displayed on the homepage?
Deepak
do we now have a plugin for this same requirement? or we need to still use manual method?
tina
Hello!
Please show how the articles of the way they are displayed in the “MORE ON RIGHT NOW WPBEGINNER” above ?? a WordPress template
Thank you
David
I turned off the organize posts by date month in settings/media, and changed url to reflect uploads directory specifically – that way I can avoid the extra step. I’m hoping this won’t cause issues with my host but it certainly makes life a little easier for me. Thank you so much for sharing this info, I have been searching for a looooong time and it’s finally how I want it
Rashid khan
hello,,, i want to add dynamic image on my wordpress home page. where al ready 5 images are set on differnet location..
i just want to replace them and add new photo by post and catorrries…
please help me
i tried but no success
i used post by thumbian function
Richard Stewart
This is great, but I failed miserably trying to implement Displaying Category Image as Default Fallback Featured Image in my classifieds theme. It uses different categories from the ‘stock’ posts categories and the author refuses to help.
Do you offer any technical services, paid or otherwise, where you can help me implement Displaying Category Image as Default Fallback Featured Image into my theme?
Matt Cromwell
This is really awesome, a really useful tip in my case. Only issue is the first code above is incomplete. Luckily I didn’t need the “if” part, so I just pulled that out and all was well.
Thanks for some pretty advanced tips on your “begginer’s” site. Keep it up!
WPBeginner Support
@Matt thanks for notifying us, we have fixed it.
Admin
Damien Carbery
Another idea could to set the post thumbnail when the post is saved. The advantage of the solution above is that the category thumbnail is easily changed.