WordPressサイトに関連投稿のリストを表示したいが、プラグインではなくコードを使いたいとお考えですか?
ブログの訪問者が興味のある投稿を読み終えたとき、関連する投稿のリストを提供することで、訪問者の興味を引きつけ、新しいコンテンツを見つけやすくなります。
この投稿では、WordPressで関連投稿をプラグイン必須でなくコードを使って表示する方法を紹介する。
なぜWordPressで関連投稿を表示するのか?
WordPressブログが成長し始めると、ユーザーが同じトピックに関する他の投稿を見つけるのが難しくなることがあります。
各ブログ記事の最後に関連コンテンツのリストを表示することは、訪問者をサイトにとどめ、ページビューを増やす素晴らしい方法です。また、人々が見つけやすい場所に最高のコンテンツを表示することで、最も重要なページの視認性を向上させることもできます。
もしあなたがコードに詳しくないのであれば、コードなしで関連投稿を表示できるWordPressの関連投稿プラグインを選ぶ方が簡単だろう。
しかし、プラグインを使わずに関連投稿を表示できないかと思ったことがある方のために、コードだけでサムネイル付きの関連投稿を生成できる2つの異なるアルゴリズムをご紹介します:
注:関連投稿にサムネイルを表示させたい場合は、まずそれらの投稿にアイキャッチ画像を追加してください。
方法1:WordPressで関連投稿をタグで表示する方法
関連コンテンツを探す効率的な方法の一つは、同じタグを共有する他の投稿を探すことです。タグは多くの場合、投稿に含まれる特定の詳細に焦点を当てるために使用されます。
このことを念頭に置いて、投稿に共通のタグを追加しておくとよいでしょう。タグはWordPressエディターの「タグ」ボックスに入力できます。
投稿にタグを追加したら、次にすることは、テーマのsingle.php
テンプレートに以下のコードスニペットを追加することです。
サイトにコードを追加する際にヘルプが必要な場合は、ウェブ上のスニペットを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();
このコードは、ページに関連するタグを探し、類似したタグを持つページをフェッチするためにデータベースクエリーを実行する。
コードはどこに貼り付けるのですか?お使いのテーマにもよりますが、ほとんどの場合、メイン投稿の後、コメント欄のすぐ上にあるテーマのsingle.phpテンプレートにコードを貼り付けることができるはずです。
私たちのデモサイトのようにTwenty Twenty-Oneテーマを使用している場合、コードを貼り付けるのに適した場所は、template-parts/content/content-single.php
ファイルのヘッダーの後、<?php the_content();
の直後です。
これにより、WordPressの投稿日に関連コンテンツが自動的に表示されます。カスタムCSSを追加して、関連投稿のスタイルと外観をテーマに一致するように変更する必要があります。
ヒント:テーマファイルを編集する代わりに、WPCodeのようなコードスニペットプラグインを使用することをお勧めします。
WPCodeは、WordPressでカスタマイザーコードを安全かつ簡単に追加することができます。さらに、投稿日の後など、WordPressサイト上の特定の場所にスニペットを自動的に挿入して実行できる「挿入」オプションが付属しています。
詳細については、WordPressでカスタムコードを追加する方法についてのガイドを参照してください。また、プラグインの詳細については、WPCodeの詳細なレビューをご覧ください。
方法2:WordPressでカテゴリー別に関連投稿を表示する方法
関連コンテンツを表示するもう一つの方法は、同じカテゴリーにある投稿をリストアップすることです。この方法の利点は、関連投稿のリストがほとんど空白にならないことです。
方法1と同様に、テーマのsingle.phpテンプレート、またはWPCodeのようなコード・スニペット・プラグインにコード・スニペットを追加する必要があります。詳しくは、方法1と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();
これで、各投稿の下に関連コンテンツのリストが表示される。
関連ページのスタイルや外観を変更したい場合は、テーマに一致するカスタムCSSを追加する必要があります。
カテゴリー: 関連投稿のエキスパートガイド
WordPressでの関連投稿の表示についてさらに詳しく知りたいですか?関連投稿に関する役立つチュートリアルをご覧ください:
- WordPressで関連投稿を表示する方法(ステップバイステップ)
- カテゴリー:WordPressで同じ投稿者の関連投稿を表示する方法
- WordPressブログ投稿にインライン関連投稿を追加する方法
- カテゴリー:WordPressでランダム投稿を表示する方法
- WordPressで関連ページを表示する方法
このチュートリアルで、WordPressでプラグインなしで関連投稿をサムネイル付きで表示する方法を学んでいただけたなら幸いです。また、WordPress サイトの訪問者をトラッキングする方法や、ウェブサイトを高速化するための 24 のヒントもご覧ください。
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.
kabir bairwa
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
WPBeginner Support
Happy to hear our guide could help you!
管理者
Jennifer
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.
aman
I want code to display random posts and pages with thumbnail
WPBeginner Support
You would want to take a look at our guide below:
https://www.wpbeginner.com/wp-tutorials/how-to-display-random-posts-in-wordpress/
管理者
karan4official
Instead of using <? use <?php everywhere
WPBeginner Support
Thank you for your feedback, this article should currently be using the php version everywhere
管理者
Motahar Hossain
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
Thanks for pointing that out, we’ll be sure to look into updating the article
管理者
Frank
Can you direct me as to where to add what categories I would like to limit the related posts to?
WPBeginner Support
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.
管理者
Greg
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
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.
管理者
Akiode obasanjo
No CSS is added
luigi
Hi, is it possible to limit them by date? Show only those of the last year?
Luis
I found a way to make the smaller thumbnails, but it shows them in a column and not horizontally. How can this be modified?
Luis
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?
WPBeginner Support
Hi Luis,
It uses the default post-thumbnail size. You can create a new thumbnail size and then use it in the code like this:
1-click Use in WordPress
管理者
Ana
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.
Musarrof
Why I’m facing this problem. syntax error, unexpected end of file
Please help me.
Mike
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.
Anthony Reese
Thanks for the tutorial. This was incredibly useful and worked like a charm!
pawan singh
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?
Ahmad
really helpful, thanks !
Tracy
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.
Victor Siyaya
I Agree. I have no idea where to paste this code too.
Rose
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
sanjeev Kumar
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
Luan
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.
Claudio
Hello!
The first link on Aditional Sources, is broken.
Thank you by the code.
WPBeginner Support
Hi Claudio,
Thank you for notifying us. We have removed the broken link.
管理者
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.
管理者
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.
管理者
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.
管理者
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.
管理者
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