Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come fare: Articoli correlati con immagini in evidenza in WordPress senza plugin

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Volete visualizzare un elenco di articoli correlati sul vostro sito web WordPress e preferite usare il codice piuttosto che un plugin?

Quando i visitatori del vostro blog hanno finito di leggere un articolo di loro interesse, offrire un elenco di articoli correlati li terrà impegnati e li aiuterà a trovare nuovi contenuti da leggere.

In questo articolo vi mostreremo come visualizzare gli articoli correlati con WordPress utilizzando il codice, senza bisogno di plugin richiesti.

How to: Related Posts with Thumbnails in WordPress Without Plugins

Perché mostrare le pagine correlate in WordPress?

Quando il vostro blog WordPress inizia a crescere, può diventare più difficile per gli utenti trovare altri articoli sullo stesso argomento.

Visualizzare un elenco di contenuti correlati alla fine di ogni articolo del blog è un ottimo modo per mantenere i visitatori sul sito web e aumentare le pagine viste. Inoltre, contribuisce a migliorare la visibilità delle pagine più importanti, visualizzando i contenuti migliori dove gli utenti possono trovarli facilmente.

Se non avete dimestichezza con il codice, allora sarà più semplice scegliere uno dei tanti plugin per i post correlati di WordPress, in grado di visualizzare gli articoli correlati senza codice.

Ma se vi siete mai chiesti se sia possibile visualizzare gli articoli correlati senza utilizzare un plugin, allora condivideremo due diversi algoritmi che potete utilizzare per generare articoli correlati con immagini in evidenza utilizzando solo il codice:

Nota: se si desidera mostrare un’immagine in evidenza per ogni articolo correlato, assicurarsi di aggiungere prima un’immagine in evidenza a tali articoli.

Metodo 1: come mostrare gli articoli correlati in WordPress in base ai tag

Un modo efficace per individuare i contenuti correlati è cercare altri articoli che condividono gli stessi tag. I tag sono spesso utilizzati per concentrarsi sui dettagli specifici contenuti in un articolo.

Tenendo conto di ciò, è possibile aggiungere alcuni tag comuni agli articoli che si desidera mettere in relazione tra loro. Potete inserirli nel box “Tag” dell’editore di WordPress.

The ‘Tags’ Settings Box in the WordPress Editor

Dopo aver aggiunto i tag ai vostri articoli, la cosa successiva da fare è aggiungere il seguente frammento di codice al template single.php del vostro tema. Se avete bisogno di aiuto per aggiungere codice al vostro sito, fate riferimento alla nostra guida su come incollare snippet dal web in WordPress.

$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>5, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
   
echo '<div id="relatedposts"><h3>Related Posts</h3><ul>';
   
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
   
<li><div class="relatedthumb"><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><!--?php the_post_thumbnail(); ?--></a></div>
<div class="relatedcontent">
<h3><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><!--?php the_title(); ?--></a></h3>
<!--?php the_time('M j, Y') ?-->
</div>
</li>
<!--?php }
echo '</ul--></ul></div>';
}
}
$post = $orig_post;
wp_reset_query();

Questo codice cerca i tag associati a una pagina ed esegue una query del database per recuperare le pagine con tag simili.

Dove posizionare il codice? Dipende dal tema, ma nella maggior parte dei casi si dovrebbe poter incollare il codice nel template single.php del tema dopo l’articolo principale e proprio sopra la sezione dei commenti.

Se si utilizza il tema Twenty Twenty-One, come nel nostro sito dimostrativo, un buon posto dove incollare il codice è il file template-parts/content/content-single.php dopo l’header e subito dopo <?php the_content();.

Related Content by Tags Preview

Questo visualizza automaticamente i contenuti correlati su qualsiasi articolo di WordPress. È necessario modificare lo stile e l’aspetto degli articoli correlati in corrispondenza del tema aggiungendo CSS personalizzati.

Related Posts example

Suggerimento: invece di modificare i file del tema, che potrebbero danneggiare il sito web, si consiglia di utilizzare un plugin per gli snippet di codice come WPCode.

WPCode rende sicura e facile l’aggiunta di codice personalizzato in WordPress. Inoltre, è dotato di opzioni di “inserimento” che consentono di inserire ed eseguire automaticamente gli snippet in punti specifici del sito WordPress, ad esempio dopo un articolo.

WPCode insertion options for custom code snippets

Per maggiori dettagli, consultate la nostra guida su come add-on di codice personalizzato in WordPress. Potete anche consultare la nostra recensione dettagliata di WPCode per approfondire chi siamo.

Metodo 2: Come mostrare articoli correlati in WordPress per categoria

Un altro modo per visualizzare i contenuti correlati è quello di elencare gli articoli che appartengono alla stessa categoria. Il vantaggio di questo metodo è che l’elenco degli articoli correlati non sarà quasi mai vuoto.

Come per il metodo 1, è necessario aggiungere uno snippet di codice al template single.php del tema o in un plugin di snippet di codice come WPCode. Per maggiori dettagli, fare riferimento al Metodo 1 e alla nostra guida su come add-on di codice personalizzato in WordPress.

$orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 2, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>
   
<li><div class="relatedthumb"><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><!--?php the_post_thumbnail(); ?--></a></div>
<div class="relatedcontent">
<h3><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><!--?php the_title(); ?--></a></h3>
<!--?php the_time('M j, Y') ?-->
</div>
</li>
<!--?php }
echo '</ul--></ul></div>';
}
}
$post = $orig_post;
wp_reset_query();

Ora vedrete un elenco di contenuti correlati in fondo a ogni articolo.

Se si desidera modificare lo stile e l’aspetto delle pagine correlate, è necessario aggiungere CSS personalizzato in corrispondenza del tema.

Speriamo che questo tutorial vi abbia aiutato a capire come visualizzare gli articoli correlati con le miniature in WordPress senza plugin. Potreste anche voler imparare a tracciare i visitatori del vostro sito WordPress o consultare il nostro elenco di 24 consigli per velocizzare il vostro sito web.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

183 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. kabir bairwa says

    I was trying to correct WordPress-related posts but it was not happening when I saw this code and I used this code in my WordPressfile so now my WordPress-related posts coming properly

  3. Jennifer says

    Is there a way to have related post based on the post title. I do not have tags and my categories really don’t do the trick since there is no distinction between them.

    This would be of great help if you had a code to show related content based on the post title.

    • WPBeginner Support says

      Thank you for your feedback, this article should currently be using the php version everywhere :)

      Admin

  4. Motahar Hossain says

    Thank you for your nice post.

    Here “ignore_sticky_posts” should be used instead of “caller_get_posts”. Because “caller_get_posts” is deprecated.

    • WPBeginner Support says

      This method limits the posts to the category the post is in. To limit the categories you would need to create an if statement to exclude certain categories.

      Admin

  5. Greg says

    Is it possible where there are more than X related posts by category that are related that you can randomise say 3 posts?

    • WPBeginner Support says

      While it is possible, it would require adding far more to this, you may want to look into a plugin for that type of customization.

      Admin

  6. Luis says

    I found a way to make the smaller thumbnails, but it shows them in a column and not horizontally. How can this be modified?

  7. Luis says

    The script is working well. The only problem I have is that the thumb-nails are very large. Would there be some way to make them smaller?

  8. Ana says

    how to do for create a shortcode for this code, I created the function but I do not know how to return the print to the page.

  9. Mike says

    Hello,
    I’m a beginner in WorldPress.
    I’d like to show Related Posts.
    In the main menu I have Category A, and in Category A – Subcategories A, B and C. The posts are in Category A, but they can also be present in all 3 Subcategories.
    When choosing one of the Related Posts something goes wrong and the posts from the initially chosen Subcategory don’t show correct anymore.

  10. pawan singh says

    Hi Admin, Very informative article. I like your site because of simplicity and straightforwardness. All articles are to the point but when it comes to sharing the knowledge of code you become too technical. Just ignore the fact that much of the visitors are not coding expert. Wouldn’t it be much better if you just add 2or 3 more lines in your explanation to make it complete and easily understandable to all. Anyway, great article But I want to know which code or plugin is Wpbeginner using?

  11. Tracy says

    what really sucks about your articles is you never actually say HOW to do something. It’s all well and good to tell me to put code into my single.php, but as a beginner I don’t know what that is or where to find it. You might want to think about putting this kind of critical information into your articles instead of assuming we know what it means, or that we have surfed every one of your articles to figure it out.

  12. Rose says

    Thanks for the great post, very useful. I came across an error in the code so wanted to share in hope it may be useful for others in the future. The error was:

    WP_Query was called with an argument that is deprecated since version 3.1.0! “caller_get_posts” is deprecated. Use “ignore_sticky_posts” instead.

    So I simply replaced it and it worked fine. I am also using namespacing so I needed to change WP_Query to \WP_Query plus I changed the order of the below:

    global $post;
    $orig_post = $post;

    Thanks again
    Rose

  13. sanjeev Kumar says

    sir
    I am using the code of categories working properly but one thing is when on home page same category of 2 or 3 post then the link show balack but i want to show to show category which is next post

  14. Luan says

    Hi,

    Thanks for your post. I added the code in content-single.php and it worked. However, it displays as 1 column not 3 columns like your example. Could you please help me on this? I want my related posts to be displayed in 1 row, 3 columns. Thanks so much.

Rispondi a Luis Annulla risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.