Abbiamo scoperto che l’impostazione di immagini in primo piano di fallback per le categorie di WordPress è un enorme risparmio di tempo, soprattutto per i blog con un elevato volume di contenuti.
Se avete articoli che non hanno un’immagine in primo piano o se volete che tutti i post di una categoria abbiano miniature simili, potete impostare un’immagine di riserva per ogni categoria.
In questo modo, potrete assicurarvi che nessun post del blog rimanga senza un’immagine in evidenza e non dovrete assegnarla manualmente a ogni singolo post.
In questo articolo vi mostreremo come impostare le immagini in evidenza predefinite di riserva per categorie specifiche in WordPress.

Perché aggiungere un’immagine in evidenza di riserva per la categoria di articoli?
Supponiamo di avere un blog WordPress in cui si assegna una singola categoria a ogni pubblica. Potete assegnare a tutti i post di quella categoria di mostrare la stessa immagine di riserva se per qualche motivo non hanno un’immagine in evidenza.
Un altro vantaggio dell’aggiunta di un’immagine di riserva per una categoria di articoli è che, se le pagine di archivio delle categorie ricevono molto traffico di ricerca, le rende più accattivanti e attraenti.
Detto questo, vediamo come aggiungere un’immagine di riserva in base alla categoria dell’articolo utilizzando un plugin per WordPress e un codice personalizzato.
Impostazione dell’immagine in evidenza di riserva in WordPress con un plugin
Di default, WordPress non offre un’opzione per aggiungere immagini alle pagine delle categorie dei post. Tuttavia, è possibile impostare facilmente un’immagine di riserva per le categorie di articoli utilizzando un plugin di WordPress.
Per prima cosa, è necessario installare e attivare il plugin Category and Taxonomy Image. Per maggiori dettagli, consultare la nostra guida su come installare un plugin di WordPress.
Dopo l’attivazione, dal pannello di amministrazione di WordPress si può andare su Impostazioni ” Immagine tassonomia. Quindi, facendo clic sul checkbox “categoria”, si possono includere le immagini della tassonomia nelle categorie degli articoli come riserva.

Non dimenticate di fare clic sul pulsante “Salva modifiche” quando avete finito.
Dopodiché, potete andare su Articoli ” Categorie dalla vostra Bacheca di WordPress. Quando si aggiunge una nuova categoria o si modifica una esistente, viene visualizzato il campo “Immagine”.

È sufficiente inserire l’URL dell’immagine che si desidera aggiungere alla categoria di WordPress. Per maggiori dettagli, consultate la nostra guida su come ottenere l’URL delle immagini caricate in WordPress.
Ora, quando si pubblica un articolo del blog senza che sia stata assegnata un’immagine in evidenza, WordPress utilizzerà l’immagine appena impostata per la categoria.
Ecco un’anteprima dell’immagine che abbiamo utilizzato sul nostro sito demo.
Tutto-in-uno! Ora avete aggiunto con successo un’immagine di riserva in base alla categoria dell’articolo.
Impostazione dell’immagine in evidenza di riserva in WordPress senza plugin
È anche possibile configurare un’immagine di riserva per le categorie di articoli senza utilizzare un plugin di WordPress. Tuttavia, questo metodo non è raccomandato per i principianti, in quanto prevede l’uso di snippet di codice.
La prima cosa da fare è creare immagini per le categorie di WordPress. Utilizzate lo slug della categoria come nome del file immagine e salvatele tutte nello stesso formato, come JPG o PNG.
Successivamente, è possibile effettuare l’upload delle immagini delle categorie sul sito WordPress da Media ” Aggiungi nuovo.

WordPress memorizzerà le immagini della categoria durante l’uploader e creerà le dimensioni delle immagini definite dal tema.
Dopo aver caricato le immagini delle categorie, è necessario spostarle in un’altra directory. Basta collegarsi al sito web con un client FTP e accedere alla cartella /wp-content/uploads/
.

Le immagini di categoria caricate saranno memorizzate nella cartella del mese, come /uploads/2022/08/
.
Aprite la cartella di questo mese.

Per maggiori informazioni, potete consultare la nostra guida su dove WordPress memorizza le immagini sul vostro sito.
Quindi, creare una cartella sul desktop del computer e chiamarla category-images. A questo punto, scaricate tutte le immagini delle categorie e tutte le dimensioni create da WordPress per esse in questa nuova cartella sul desktop.
Una volta terminato il download, è necessario caricare la cartella category-images nella directory /wp-content/uploads. In questo modo sarà possibile avere tutte le immagini delle categorie in una cartella separata, facile da richiamare nel tema.
Per maggiori dettagli, consultate la nostra guida su come utilizzare l’FTP per l’uploader dei file su WordPress.
Visualizzazione dell’immagine della categoria come immagine in evidenza predefinita di riserva
In seguito, vi mostreremo come visualizzare una di queste immagini come immagine in evidenza di riserva quando un articolo di una categoria non ne ha una impostata.
Questo metodo comporta il copia e incolla del codice e di norma non consigliamo agli utenti di modificare i file del tema. Piccoli errori possono causare grandi errori sul sito.
Un modo più semplice per aggiungere codice al vostro sito è utilizzare WPCode. È il miglior plugin per gli snippet di codice di WordPress, che consente di gestire in modo sicuro e semplice il codice personalizzato sul sito.
Per prima cosa, è necessario installare e attivare il plugin gratuito WPCode. Per maggiori dettagli, consultate la nostra guida su come installare un plugin di WordPress.
Successivamente, si può andare su Code Snippets ” + Add Snippet nel pannello di amministrazione di WordPress per aggiungere un nuovo snippet. Quindi fate clic sul pulsante “Add New”.

Successivamente, è possibile aggiungere codice personalizzato o utilizzare uno snippet della libreria WPCode.
A tale scopo, si utilizzerà il proprio codice personalizzato, quindi passare al passaggio del mouse sull’opzione “Aggiungi il tuo codice personalizzato (nuovo snippet)” e fare clic sull’opzione “Usa snippet”.

Successivamente, è necessario selezionare “PHP Snippet” come tipo di codice dall’elenco di opzioni che appare sullo schermo.

Aggiungete ora un nome per il vostro snippet, che può essere qualsiasi cosa per aiutarvi a ricordare a cosa serve il codice.

A questo punto, è sufficiente copiare il seguente frammento di codice e incollarlo nel campo “Anteprima codice”.
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(); }); });"; } } |
Quindi, si può scendere alla sezione “Inserimento” e scegliere “Inserimento automatico” per lasciare che il plugin gestisca il posizionamento per voi.
Quindi, scegliere l’opzione “Inserisci prima del contenuto” nella sezione “Pagina, Post, Tipo di contenuto personalizzato” nel menu a discesa “Posizione”.

È quindi possibile ritornare in alto nella pagina e cambiare la levetta da “Inattivo” ad “Attivo”.
Facendo clic sul pulsante “Salva snippet” in alto, l’immagine di riserva sarà pronta.

Si consiglia di consultare anche la nostra guida su come add-on di snippet di codice personalizzati in WordPress.
Nota: questo frammento di codice funziona solo con la tassonomia “categoria”. Tuttavia, è possibile aggiungere altre tassonomie aggiungendo il loro nome all’elenco nella classe follower del codice e cambiando il termine tra parentesi in “tagga” o “articolo”, per esempio.
1 | protected static $taxonomies = [ 'category' ]; |
Al termine, basta visitare il sito web per vedere l’immagine di riserva.
Speriamo che questo articolo vi abbia aiutato ad aggiungere un’immagine di riserva in base alla categoria del post. Potete anche consultare la nostra guida su come aggiungere una barra di avanzamento nei post di WordPress e la nostra scelta delle migliori alternative a Canva per la grafica dei siti web.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e 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.