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.
Perché mostrare le pubblicazioni 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 i post correlati senza usare un plugin, condivideremo due diversi algoritmi che potete usare per generare post correlati con immagini in evidenza usando 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.
Dopo aver aggiunto i tag agli articoli successivi, la cosa da fare è aggiungere il seguente frammento di codice al template single.php
del 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();.
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.
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.
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.
Guide di esperti sui post correlati in WordPress
Volete approfondire la visualizzazione dei post correlati in WordPress? Selezionate questi utili tutorial sui post correlati:
- Come visualizzare le pubblicazioni correlate in WordPress (passo dopo passo)
- Come visualizzare le pubblicazioni correlate dello stesso autore in WordPress
- Come aggiungere post correlati in linea nei post dei blog WordPress
- Come visualizzare le pubblicazioni casuali in WordPress
- Come mostrare le pagine correlate in WordPress
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.
Syed Balkhi
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!
Abhijit Badgujar
Hi,
I have a ‘Related post’ option from my wordpress theme and i am already using it. I have displayed 6 posts after the content. The problem is, it only shows 3 related posts and next three can be seen when you slide it horizontally. I don’t want that option, i want the site to display all 6 posts outright. Can you tell me how to do it?
Gyuricza Laszlo
Hello,
Your guidance was amazing but how can i exclude a specific category from the related posts in order to not display it?
Thank you, in advance!
Sincerely,
LAszlo Gyuricza
WPBeginner Support
You can try one of the related posts plugins.
Admin
Tuta
Hi Syed. How do I style it?
WPBeginner Support
Hi Tuta,
You can use #relatedposts .relatedthumb and .relatedcontent selectors in your CSS to style it.
Admin
Dev Rathore
How to Display All Post List in one Page
Suraz
How to Show Related Post It In two Columns Like here in WPBeginner??
Tom
Nice solution but not definitive for my exigence. Infact the mean problem is that this code sort the related posts from the most recent in the same category or tags. The result is that when you browse inside a category/tag you’ll always display the same few last posts, limiting hardly the older posts of your site. That’s a right conclusion? Please if you tried it share your opinion!
Joy
1. After ‘caller_get_posts’=>1 put a comma(,)
2. Hit enter button [next line]
3. Add ‘orderby’=>’rand’
You are done. Now related posts will be shown randomly. Thank you.
Zane DeVault
This code works great. I was wondering if you could explain what this part of the code does?
$orig_post = $post;
global $post;
…
$post = $orig_post;
I think I have a grasp on what the rest is doing, but this is throwing me for a loop.
Thanks for all your great content!
may nghe len
Let me ask the Code Related Posts by Category posted in public places. thank you
atiq
in Twentyfifteen default theme where should i insert this code in single.php file? If i inserted above the endwhile; it shows syntax error, unexpected ‘endwhile’ and if i inserted below the endwhile; but above the endif; it shows syntax error, unexpected ‘endif’
Any solution for this?
Thanks
Mohammad Kazemi
You must use ‘<?php' not '<?'
atiq
in Twentyfifteen default theme where should i insert this code in single.php file? If i inserted above the enwhile; it shows syntax error, unexpected ‘endwhile’ and if i inserted below the enwwile but above the endif; it shows syntax error, unexpected ‘endif’
Any solution for this?
Thanks
Marcel Tripoux
Hi! Great post!
Is there a way to combine both option, in order to call related tags only in the current category ?
Bambang
my single.php layout :
//the_content bla bla bla code here
//Copy paste Related Posts by Tags code here
//comments_template bla bla bla code here
——————————-
the result i got error :
Parse error: syntax error, unexpected ‘endwhile’ (T_ENDWHILE) in …
——————————-
after i change ” <? } " to " <?php } " it worked,
just sugestion, maybe it better if you put complete php open tag
thanks
Alex
Works perfect. How to exclude the definite tag from Related Posts by Tags? I mean how to change the code when algorithm would find other posts with any one of the tag (except tag 595 for instance) that the current post has and will list them.
Mohammad
Thanks for the great code
It works great but you didn’t address any css codes for a more beautiful look for this section. Can you please do this? I’m newbie to coding and I tried some codes but they didn’t work. In your codes there is:
echo ‘Related Posts’;
but in some similar codes I found in other resources there is:
and in css some codes like this:
.relatedposts {
font-size: 12px;
width: 640px;
}
.relatedposts h3 {
font-size: 20px;
margin: 0 0 5px;
}
will get that a nice look but it didn’t work with your code.
Thanks
Muthu
Dear collegue this is an error am getting while pasting this code on single.php file.kindly tell me exacctly where should i paste this code.
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\beingusefull\wp-content\themes\TechPlus\single.php on line 78
WPBeginner Staff
That will depend on your individual theme and template. You need to add the conditional tag after the WordPress loop begins. After this line:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
Jenny
I got that error too and this is my updated code:
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.
‘caller_get_posts’=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) { ?>
Related Posts
have_posts() ) : $my_query->the_post(); ?>
<a href="” rel=”bookmark” title=””>
<a href="” rel=”bookmark” title=””>
wiyono
When the post i share on facebook, the thumbnail getting from related post, can i get the thumbnail from the main page? thx
Lacey Tech Solutions
If you’re using Yoast’s WordPress SEO plugin you can specify the thumbnail URL under the social tab for the post. If the social tab isn’t shown then you need to click the Yoast SEO link in the WordPress admin menu then click “Social”. In the social page tick the option for, “Add Open Graph meta data” and save. Go back into your post and you can specify the thumbnail image you want to use when the post is shared. If you don’t implicitly set the post image the user has the option of selecting any image that appears on the page, which is why your recent post images are being pulled in when you share the article link.
Gretchen Louise
Any thoughts on how much of a database/server load this would be on a large self-hosted site? Looking for a related posts alternative now that #nRelate is no longer available.
WPBeginner Staff
Use conditional tag if (is_single()) on the first line of the code.
vipul
can you tell where and how?
Rachael
This doesn’t work in the single.php for me, b/c related posts show up at the very bottom of the page. It works with loop.php but then they also show up on the homepage – any ideas on a fix so it just shows in single posts and not the homepage?
kate // always craving //
Hi, I must be the only one who is not doing this correctly. My theme supports featured images, I added this code before the comments within the single.php file. Any tips on exactly where to input in the code?
Keyko Sakura
All the codes I find never work. Or they don’t change anything on my page or they display an error message. I don’t know what else to do!
Mason Coulter
Is there a way to add pagination to the related posts query? I cant seem to get pagination to work on a secondary query within single.php. Thanks!
Tom K.
Hello , i want to ask , is there way to make , that related posts would be by category and tags in one place? Thanks.
Jonas
My thumbnails are too big, help. How can you limit the related posts thumbnails?
WPBeginner Support
You probably need to regenerate thumbnails.
Admin
Jonathan
Is there a way to choose a single category (let’s call it Brands) and then have it display related posts only affiliated with the child categories under Brands? So, the hierarchy for the cats would be Brands > JCPenny. I want to only show related posts for JCPenny. But, that child category could be different per post. So if a post uses a different child category it’ll show related posts for that child cat. Can this code be modified to handle that somehow?
Jonathan
OH! I think I’ve got it. I just added ‘parent’ => ‘the cat id number’, to the args and I think that did it.
Jonathan
wait… no, that didn’t work
Miro
Hi, thanks for the code, but instead of grabbing the featured image as a thumb, can i grab instead the first image in my posts? Thanks
WPBeginner Support
This sounds like a nice post idea, we will cover it soon in a new article. Thanks for the feedback.
Admin
Miro
It would be great if you guys would make a post on it. Thank you very much and will be waiting. Hope that you can kindly post here a notification once you made the post so we know.
Caleb
Great post thanks! I run a website that uses WP more as a CMS with a large number of pages rather than posts. Can I do this with as related pages instead, so that it’s grabbing related pages and not posts? If so how do I go about doing this.
Thanks for the help
Muhammad Hadi Qureshi
Really thanks for this helping post
Phil Simon
This. Is. Awesome. WPEngine understandably doesn’t allow for related posts plugins, save for a few exceptions. I tried a few and really didn’t like them. I threw this code into single.php and voila! Thank you.
Lucas Bishop
This is good, but i wanna do it with title of post rather then tags or category. Any suggestions for it, syed!!
Alexandros
Hi friends little problem it appears to me: “Parse error: syntax error, unexpected ‘endwhile’ (T_ENDWHILE) in C: \ xampp \ htdocs \ z1 \ wp-content \ themes \ mytheme \ single.php on line 65” find
But what ..? Thanks
WPBeginner Support
Try pasting the code below the endwhile; in your single.php file.
Admin
Britt
Love this piece of code, use it on the regular! One question: Is there a way to exclude some tags in the code?
Rakesh
Take a look at the category related posts code. It wont work unless you add some php , the three letters before getting started with echo. Add php and it will not be ignored. In either case, it is ignored and wordpress cries every time with an error note. Thanks for the code by the way and it made my work a lot easier. Thanks a ton for that and do adjust it ,
Dennis
Also, I have one more question,
What if I wanted to display a certain post containing a certain tag to all posts, how would I do this?
Dennis
Hi, this is so awesome! Now I can just get rid of my related post plugin, so thanks A LOT for that!
One question I have is, how can I display the related post in 2 column?
Once again, this has been such a BIG help for me!
Christina
Hi!! Thanks for your helpful information for those, like myself, who have no idea of any coding, but still want to have a blog!! I have just incorporated your ‘relate posts by tags” code to my single post file. It works except for the pfotos. They dont show at all and the titles of my related posts are shown the one under the other, like a list. What have I done wrong?? Thanks in advance for your answer!!
WPBeginner Support
It seems like you are not using post thumbnails or featured images with your posts in WordPress. Also you may need to tweak the CSS a little bit/
Admin
TheFran
Hi,
This code is amazing! Thank you so much. Is there a way I can make the code show related posts from ANOTHER SITE? So it searches the posts from another site that I show below the post as a related post on my site?
Thanks!
Editorial Staff
Not using this snippet. You would have to create something more complex for that.
Admin
Carlos
Hi,
I’m using a theme that works with custom posts. I wonder if I try your code, which part should I edit to display just those custom posts instead of the regular posts.
Thanks
Miz.Chellie
Hello – yours is the first tutorial that I found that works but I would like the list vertical. Can you give an example of the CSS for that?
Livius
Hey,
I cannot, find the single.php where I have to insert this code.
The problem is that I am using Balance Theme + Genesis. So in the genesis, I can find the Single.php, but it says to “Not Edit Under Any Circumstances”, and I have actually pasted the code in there, but it made my site to stop opening pages at all.
And in the Child Balance Theme, there is no Single.php ….
Any suggestions?
Editorial Staff
Yes, don’t edit the framework file. You would have to familiarize yourself with Genesis hooks and filters. Then add the code in one of the loop hooks for single page using your functions.php file. Unfortunately, due to the amount of frameworks out there, we can’t possibly cover our tips for all frameworks.
Admin
Mark
Use Genesis Hooks then put the code in there.
peter
Hello is there any way to change the thumbnail size? i get only one related post and its thumbnail is huge
Editorial Staff
Yes. You would have to add additional image sizes like this:
https://www.wpbeginner.com/wp-tutorials/how-to-create-additional-image-sizes-in-wordpress/
Admin
Dean
Hi! this is very useful coding. Is it possible to use this for making a custom page that will show all the posts, like a sitemap but with thumbnails? Something like this:
Category 1
—– related posts code (all posts from that category) ——
Category 2
—– related posts code (all posts from that category) ——
etc. It would make a great showcase for categories with few posts. Thank you for reading and help!
Dean
hey, found something here.. I will try that
Nuno Marques
Hey,
very handy your “Related Posts by Category”.
Sometimes I believe it’s better to have add a raw code rather than use a plugin doesn’t is so expansible…
Thank you!
Silverbadger
Is it possible to display the posts horizontal instead of vertical?
Thanks
Editorial Staff
Yes, you can simply adjust the CSS.
Admin
Paul
Thank you thank you thank you!! A simple copy paste bit of code that just gets on with it and works – does exactly what it says. This is exactly what I was looking for
Editorial Staff
Yes, you can use post thumbnails by itself. Not sure why you would want the related feature…
Admin
Raheek
Thanks for the helpful article. I now just added elated posts by using this code.
Ferdy
What if there are no related posts. can it be coded such that it falls back to category related.
tobalseverin
hi!
i need some help…
How i can filter.. the category, but if i have parent and child categories and only i show the child post. ex:
– product (all product, this is the parent) (id 104)
– KindOfProducts (subcategory, this is the child) (id 109)
– KindOfProductsTwo (subcategory, this is the child) (id 110)
in products have all post but just need show related from the child: KindOfProducts.
i try whit this:
$args = array(
‘category__in’ => $category_ids,
‘category__not_in’ => 104,
‘post__not_in’ => array($post->ID),
‘orderby’=> ‘rand’,
‘showposts’ => 100,
‘ignore_sticky_posts’ => 1
);
but dont showme nothing…
and i try whit this other one:
$args = array(
‘category__in’ => $category_ids,
‘child_of’ => 104,
‘post__not_in’ => array($post->ID),
‘orderby’=> ‘rand’,
‘showposts’ => 100,
‘ignore_sticky_posts’ => 1
);
and nothing
help? tnks!