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

方法WordPressでプラグインを使わずにサムネイル付きの関連投稿をする。

WordPressサイトに関連投稿のリストを表示したいが、プラグインではなくコードを使いたいとお考えですか?

ブログの訪問者が興味のある投稿を読み終えたとき、関連する投稿のリストを提供することで、訪問者の興味を引きつけ、新しいコンテンツを見つけやすくなります。

この投稿では、WordPressで関連投稿をプラグイン必須でなくコードを使って表示する方法を紹介する。

How to: Related Posts with Thumbnails in WordPress Without Plugins

なぜWordPressで関連投稿を表示するのか?

WordPressブログが成長し始めると、ユーザーが同じトピックに関する他の投稿を見つけるのが難しくなることがあります。

各ブログ記事の最後に関連コンテンツのリストを表示することは、訪問者をサイトにとどめ、ページビューを増やす素晴らしい方法です。また、人々が見つけやすい場所に最高のコンテンツを表示することで、最も重要なページの視認性を向上させることもできます。

もしあなたがコードに詳しくないのであれば、コードなしで関連投稿を表示できるWordPressの関連投稿プラグインを選ぶ方が簡単だろう。

しかし、プラグインを使わずに関連投稿を表示できないかと思ったことがある方のために、コードだけでサムネイル付きの関連投稿を生成できる2つの異なるアルゴリズムをご紹介します:

注:関連投稿にサムネイルを表示させたい場合は、まずそれらの投稿にアイキャッチ画像を追加してください。

方法1:WordPressで関連投稿をタグで表示する方法

関連コンテンツを探す効率的な方法の一つは、同じタグを共有する他の投稿を探すことです。タグは多くの場合、投稿に含まれる特定の詳細に焦点を当てるために使用されます。

このことを念頭に置いて、投稿に共通のタグを追加しておくとよいでしょう。タグはWordPressエディターの「タグ」ボックスに入力できます。

The ‘Tags’ Settings Box in the WordPress Editor

投稿にタグを追加したら、次にすることは、テーマの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();の直後です。

Related Content by Tags Preview

これにより、WordPressの投稿日に関連コンテンツが自動的に表示されます。カスタムCSSを追加して、関連投稿のスタイルと外観をテーマに一致するように変更する必要があります。

Related Posts example

ヒント:テーマファイルを編集する代わりに、WPCodeのようなコードスニペットプラグインを使用することをお勧めします。

WPCodeは、WordPressでカスタマイザーコードを安全かつ簡単に追加することができます。さらに、投稿日の後など、WordPressサイト上の特定の場所にスニペットを自動的に挿入して実行できる「挿入」オプションが付属しています。

WPCode insertion options for custom code snippets

詳細については、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 サイトの訪問者をトラッキングする方法や、ウェブサイトを高速化するための 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.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

アバター

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.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

182件のコメント返信を残す

  1. imranhunzai

    Absolutely awesome! and yeah it helps.

  2. 8MEDIA

    amazing post ,, thanks :D

  3. shaileshtr

    It is good to show related post in wordpress blog without plugiN. iIt will consume less bandwidth and time to load. http://shareitto.com Thanks for your suggestion.

  4. zioneyemedia

    I do have a question on this: I’m wrestling on the code to capture posts from child categories versus parent categories. Any advice?

  5. AmandaLong

    This rocks … Thanks!

  6. dustinporchia

    I’m trying to use the related posts by category and I noticed that you said the code has to come before the comments in the main loop. In my code I want the related posts to come after the comments in the loop. When I do this I notice my disqus comment plugin takes longer to load now. Is that because of an error with the comments or is that normal?

    • dustinporchia

      Nevermind…I just switched to livefyre as this is more of what I’m looking for in a comment system anyways…thanks!

  7. subzerokh

    please

    could someone help a newbie like me customize this script so it’ll display related post in an horizontal way?

    from left to right..

    instead of currently showing it from up to down, vertically…

    • zioneyemedia

      Hey,

      How I did it is I replaced the and codes with my own html and css. The codes create lists for each post, and that is usually in a vertical fashion.

      ——————

      <a href="” rel=”bookmark” title=””> <a href="” rel=”bookmark” title=””>

      ——————

      I replaced the opening with and replaced the closing with as my html tags. Then I write my CSS to fit that specific div class needs on your website. For example, a sample pleft class could look like this:

      .pleft {float:left; padding:2px; margin:10px; width:278px; height:190px;}

      I use the float: selector on my CSS to move posts horizontally, and the margins and padding to give each post spacing within each other. I added in a specific width and height for additional examples.

      Hope this helps.

  8. gcog

    I’ve got related tags for sure, but when I add the code I see nothing. Also, when I add your code to restrict to a custom post type, it gives me an error. I did change the post type to my specific post type.

  9. subzerokh

    @wpbeginner hello

    thanks for your quick answer…

    but i’m a real novice at all you are saying..

    can you please give a litlle exemple?

    for making them horizontal as on your own blog?

    can get in touch by my mail: khiloc at gmail dot com

  10. wpbeginner

    @subzerokh You would have to edit the styling. It is not that hard. Simply wrap each post in a div. Specify a width for that div and then set a float left property. Adjust the margins and such and you have it.

  11. subzerokh

    hello all!! thanks for this wonderfull script!!

    It’s the only thing i found doing exactly what i wanted!!!

    But it’s just showing related post in vertical way (from up to down)

    I would like it to be shown from left to right (horizontally)

    How to do that please??

  12. ConnectIndia

    Error Fatal error: Call to undefined function the_post_thumbnail() in /home/connec92/public_html/wp-content/themes/weekly/single.php on line 59 Can some one help. website http://www.connectindia.co.in

  13. xavpro

    hey,

    great post! maybe you could help me:

    i have a auto thumb if none is defined,

    if ($thumb_array[‘thumb’] == ”) $thumb_array[‘thumb’] = ‘link to your default thumbnail image’;return $thumb_array;

    now my question is how to define a thumb for each category, which will be used if none is defined at post.

  14. dehahs

    works nicely, thanks for sharing!

  15. AdnanAsif

    Hi

    thanks for your great post..

    But any change to get posts by categories but not in ul and li and not in thumb..

    I mean full posts show in related posts..just like show on home page, with readmore link.

    thanks

    waiting your reply..

  16. AdnanAsif

    Hi

    thanks for your great post..

    But any change to get posts by categories but not in ul and li and not in thumb..

    I mean full posts show in related posts..just like show on home page, with readmore link.

    thanks

    waiting your reply..

  17. ibadullah25

    Can I have a CSS For this please

    • Editorial Staff

      The CSS we used was for a client’s site. You can add your own CSS on how you want to display this.

      管理者

  18. titusmagnet

    Thanks..im searching for this kinda Code

  19. jaffa

    This is great, just what I have been looking for. I wonder though, how could I combine the two above and if there are no tags then it displays posts from the same category?

    Trying to figure this out but not getting very far yet

  20. nikbanks

    Thanks for the code it worked but how do I style it. I’d like it to be 4 stories side by side like yours. It is listed one on top of another on my site and not listed like yours.

    • Editorial Staff

      That is CSS. We are not using this code to show related stories. Second, i believe what you are talking about is featured stories on our sidebar. We have written another post about that in our site.

      管理者

  21. Coolguy

    is ther a way to dispay the thumbs in related post without using featured images or post thumbs??
    i.e to use any image used in the post …

    • Editorial Staff

      Yes, you can utilize the fallback techniques shared by other developers which pulls the first image from the post. But we recommend using the WordPress post thumbnails…

      管理者

  22. Hetal

    Thanks for this article. I was wondering if there is a way to auto-tag posts without having to manually enter them.

  23. Sisko

    Great!
    What if I want to display related posts by category without thumbnails?
    Thanks

  24. Terry

    Thank you for posting this tutorial, it helps me a lot.

  25. Adrian

    Hi there…Just wanted to say that I’ve been building my wordpress website from the ground up and this code works perfectly for me using WP 3.1….All I need to do now is style the CSS and get some thumbnails happening for the posts. Thanks for your help with the code.

  26. Patricia

    Hi, is there a way to exclude categories? I have two main categories where all the categories get assigned to. The main categories have sub-categories and I would like to show just related posts from the sub-categories.

    Is this possible, by excluding the id’s of the main categories?

    Thanks for your advice!

    BTW…love the code…and it works great!!!

  27. usman

    I was searching for related post with thumbnails plugins but the code that you paste above, solve my problem.

  28. John

    Just one question, is there a way to only pull tags from the same post type? Maybe using something like ‘post_type=videos’?

    • John

      By the way, got this figured out as well:

      Just add it to the array:

      $args=array(
      ‘category__in’ => $category_ids,
      ‘post__not_in’ => array($post->ID),
      ‘posts_per_page’=> 2, // Number of related posts that will be shown.
      ‘caller_get_posts’=>1,
      ‘post_type’=>’videos’
      );

  29. marion

    Hi,

    Thank you for this tutorial. I’m wondering though if there’s anyway the related products can be randomized? I’ve checked different products in the same category and the same related products were shown.

    Thanks

      • phdean

        Hi,

        I too would like to randomize the posts that display for the categories as, otherwise, they’ll display the same 2 every time. Can you please give me the code to do this?

        Many thanks in advance :)

  30. John

    Nevermind, I got it figured out. Thanks for the post!

      • John

        I didn’t have any other posts with the same tags, i.e. no related posts. Dummy mistake.

  31. John

    I copied this code and put it in my single.php without changing a thing and nothing gets outputted. Anything wrong with my code? pastebin.com/kg0SkrAg

  32. James

    This doesn’t bring up a thumbnail — there isn’t even a call for an image int eh code. I don’t see how anyone can get this to work.

    • Editorial Staff

      The code for the image is: the_post_thumbnail(); << This is not static html where you will see img src code. The function calls in the database to search for a featured image aka thumbnail that is attached to each article. If found, it will output the image. Now if you do not have post thumbnails enabled in your theme, then you need to add it first:

      https://www.wpbeginner.com/wp-themes/how-to-add-post-thumbnails-in-wordpress/

      The article clearly stated that in the Note: section. You should consider reading it thoroughly.

      管理者

  33. Roberto Silva

    hey man, I love your blog!

    I have a question?

    Can you do the same trick but ” BY Author” ?

    showing the latest posts by author?

    you will save my life :-)

    Btw thanks for this website!

      • Roberto Silva

        yessss, thanks…

        It will be a great article.

        bacause “latest posts by author without plugin” is hard to find on internet.

        you are the best.

  34. Quinn

    Thanks for this code! I’ve given it a try and it works somewhat.

    I can get it to give a listing of the related articles, a huge benefit.

    But I can’t seem to get any images to show up.

    The articles have images if this code scrapes.

    I also went in and created images for each post with the custom tag “relatedthumb”. But alas, still no images.

    Is there something else I need to do?

    Many thanks in advance!

    Quinn

    • Editorial Staff

      This trick is using the default WordPress thumbnails which was added in WP 2.9. If you have an image attached as that thumbnail, then it will pull it.

      管理者

  35. Anthony

    Is it possible to exclude a category from this module ?

    Thanks a lot,
    Anthony

    • Editorial Staff

      It will only shows post on the category that the other post resides in…

      管理者

  36. Madhav Tripathi

    Hi, thanks for this good tutorial, currently I am using Thesis theme, so I want to know if there is a way in thesis theme implement this .php code.

  37. Sophie

    I’m trying to modify his code in order to use it with categories within a custom post type. Can anyone help? I’m fairly new to php.

    Thanks!

  38. rulethenation

    ok i got it to work, is there anyway to put a default pic if a thumbnail is unavailable

    • Editorial Staff

      Yes, you can use the if paramter to check if there are plugins… if not then you can display a default image.

      管理者

        • Quickbrown

          In order to use default images when no post thumbnail available, replace with <?php if (has_post_thumbnail()) {the_post_thumbnail()} else {echo '’;} ?>
          Then put a default-image.jpg under your themes’ image folder.

  39. rulethenation

    i cant get this to work, it just messes up my whole layout near the comments, am i missing something? i had to take it off my site

  40. Heather Hill

    HI!
    Thanks for this information! This is exactly what I was looking for.
    Is there a way to add an excerpt to this, along with the photo?

    Thanks again for your help!

  41. Jez

    Thanks for this, exactly what I was looking for! I love how straight to the point your articles are, no confusion.

  42. Omer Greenwald

    Thanks for sharing. I’m using this code for a while now but it has a problem: when adding tags to a post, WP sorts them alphabetically regardless of the priority I added them. So this code displays related posts matching the first tag only which are less relevant sometimes.
    Maybe you have an idea how to prevent this auto sorting of tags by WordPress or any other solution?

  43. Doug C.

    All that first code did was put two instances of the same post on the page. It didn’t show any related anything.

    • Editorial Staff

      Doug please contact us using the form with a live link example, and we can help. We know this code is working because a few of our client’s site is using it.

      管理者

  44. Noor

    Very use article, thanks for updating

  45. Liam

    Great tutorial. Would someone mind showing me a working single.php with this code?

    I’m still learning php.

    Unfortunately
    Parse error: syntax error, unexpected T_ENDIF in C:\xampplite\htdocs\mock\wp-content\themes\scwd\single.php on line 76

    • Editorial Staff

      Here is a working example Flowtown Blog.

      Note that this code is so it will work inside the loop. Where are you trying to post this? If it is outside the loop then just add the end if code endif; << like that.

      管理者

        • Editorial Staff

          Don’t know what could be going wrong. After the clearfloat class it should work fine. That is how we put it in flowtown and it is working perfectly.

        • Liam

          I will finish the theme and try it on a live site instead of xamp. I will let you know.

  46. Shahab

    Nice tutorial!
    Right now i am using YARPP but would love to give this a try!
    Thanks

  47. Vivek @ InfoEduTech

    Thanks for this article. i am searching for lot of time to show the thumbnails with my article i am unable to perform this. i have tried many wordpress plugin but couldn’t done this. hope this might help me out

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。