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

Jak to zrobić: Powiązane wpisy z miniaturkami w WordPress bez wtyczek

Uwaga redakcyjna: Otrzymujemy prowizję z linków partnerskich na WPBeginner. Prowizje nie mają wpływu na opinie i oceny naszych redaktorów. Dowiedz się więcej o Proces redakcyjny.

Czy chcesz wyświetlić listę powiązanych wpisów na twojej witrynie internetowej WordPress i wolisz używać kodu zamiast wtyczki?

Gdy odwiedzający twojego bloga skończą czytać interesujący ich artykuł, zaoferowanie listy powiązanych wpisów utrzyma ich zaangażowanie i pomoże im znaleźć nowe treści do przeczytania.

W tym artykule pokażemy, jak wyświetlić powiązane wpisy w WordPressie za pomocą kodu, bez konieczności korzystania z wtyczki.

How to: Related Posts with Thumbnails in WordPress Without Plugins

Dlaczego warto wyświetlać wpisy powiązane w WordPress?

Kiedy twój blog WordPress zaczyna się rozrastać, użytkownikom może być trudniej znaleźć inne wpisy na ten sam temat.

Wyświetlanie listy powiązanych treści na końcu każdego wpisu na blogu to świetny sposób na zatrzymanie odwiedzających na twojej witrynie internetowej i zwiększenie liczby odsłon. Pomaga również poprawić widoczność twoich najważniejszych stron, wyświetlając najlepsze treści tam, gdzie ludzie mogą je łatwo znaleźć.

Jeśli nie jesteś obeznany z kodem, to łatwiej będzie ci wybrać jedną z wielu wtyczek WordPress do wyświetlania wpisów powiązanych bez kodu.

Ale jeśli kiedykolwiek zastanawiałeś się, czy możesz wyświetlać powiązane wpisy bez użycia wtyczki, podzielimy się dwoma różnymi algorytmami, których możesz użyć do generowania powiązanych wpisów z miniaturami za pomocą samego kodu:

Uwaga: Jeśli chcesz wyświetlać miniaturkę przy każdym powiązanym wpisie, upewnij się, że najpierw dodałeś obrazek wyróżniający do tych wpisów.

Metoda 1: Jak wyświetlić powiązane wpisy w WordPressie za pomocą tagów?

Jednym ze skutecznych sposobów na zlokalizowanie powiązanych treści jest wyszukiwanie wpisów, które mają te same tagi. Tagi są często używane do skupienia się na konkretnych szczegółach zawartych we wpisie.

Mając to na uwadze, możesz dodać kilka wspólnych tagów do wpisów, które chcesz ze sobą powiązać. Możesz je wpisz w polu „Tagi” w edytorze WordPress.

The ‘Tags’ Settings Box in the WordPress Editor

Po dodaniu tagów do twoich wpisów, następną rzeczą do zrobienia jest dodanie następującego fragmentu kodu do szablonu single.php twojego motywu.

Jeśli potrzebujesz pomocy w dodaniu kodu do twojej witryny, zapoznaj się z naszym przewodnikiem na temat wklejania fragmentów kodu z sieci do WordPressa.

$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();

Ten kod szuka tagów powiązanych ze stroną, a następnie uruchamia zapytanie do bazy danych w celu pobrania stron z podobnymi tagami.

Gdzie należy umieścić kod? To zależy od twojego motywu, ale w większości przypadków powinieneś być w stanie wkleić kod do szablonu single.php twojego motywu po głównym wpisie i tuż nad sekcją komentarzy.

Jeśli korzystasz z motywu Twenty Twenty-One, tak jak my na naszej witrynie demonstracyjnej, dobrym miejscem do wklejenia kodu jest plik template-parts/content/content-single.php po nagłówku i zaraz po <?php the_content();.

Related Content by Tags Preview

Spowoduje to automatyczne wyświetlanie powiązanych treści w dowolnym wpisie WordPress. Będziesz musiał zmienić styl i wygląd powiązanych wpisów, aby dopasować je do twojego motywu, dodając własny CSS.

Related Posts example

Wskazówka: Zamiast edytować pliki motywu, co może zepsuć twoją witrynę internetową, zalecamy użycie wtyczki fragmentów kodu, takiej jak WPCode.

WPCode umożliwia bezpieczne i łatwe dodawanie własnego kodu w WordPress. Ponadto zawiera opcje „Insertion”, które pozwalają automatycznie wstawić i wykonać fragmenty kodu w określonych miejscach na twojej witrynie WordPress, na przykład po wpisie.

WPCode insertion options for custom code snippets

Aby uzyskać więcej informacji, zapoznaj się z naszym przewodnikiem na temat dodawania własnego kodu w WordPress. Możesz również sprawdzić naszą szczegółową recenzję WPCode, aby dowiedzieć się więcej o wtyczce.

Metoda 2: Jak wyświetlić powiązane wpisy w WordPressie według kategorii?

Innym sposobem wyświetlania powiązanych treści jest lista wpisów, które znajdują się w tej samej kategorii. Zaletą tej metody jest to, że lista powiązanych wpisów prawie nigdy nie będzie pusta.

Podobnie jak w metodzie 1, musisz dodać fragment kodu do szablonu single. php twojego motywu lub we wtyczce fragmentów kodu, takiej jak WPCode. Aby uzyskać więcej informacji, zapoznaj się z Metodą 1 i naszym przewodnikiem na temat dodawania własnego kodu w 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();

Teraz zobaczysz listę powiązanych treści na dole każdego wpisu.

Jeśli chcesz zmienić styl i wygląd powiązanych stron, będziesz musiał dodać własny CSS, aby dopasować go do twojego motywu.

Chcesz dowiedzieć się więcej o wyświetlaniu powiązanych wpisów w WordPress? Sprawdź te pomocne poradniki dotyczące powiązanych wpisów:

Mamy nadzieję, że ten poradnik pomógł ci dowiedzieć się, jak wyświetlać powiązane wpisy z miniaturkami w WordPressie bez wtyczek. Możesz również dowiedzieć się, jak śledzić odwiedzających twoją witrynę WordPress lub zapoznać się z naszą listą 24 wskazówek, jak przyspieszyć twoją witrynę internetową.

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.

Ujawnienie: Nasze treści są wspierane przez czytelników. Oznacza to, że jeśli klikniesz na niektóre z naszych linków, możemy otrzymać prowizję. Zobacz jak WPBeginner jest finansowany, dlaczego to ma znaczenie i jak możesz nas wspierać. Oto nasz proces redakcyjny.

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.

Najlepszy zestaw narzędzi WordPress

Uzyskaj BEZPŁATNY dostęp do naszego zestawu narzędzi - zbiór produktów i zasobów związanych z WordPressem, które każdy profesjonalista powinien mieć!

Reader Interactions

183 komentarzeZostaw odpowiedź

  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 :)

      Administrator

  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.

      Administrator

  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.

      Administrator

  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.

  15. Abhijit Badgujar says

    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?

  16. Gyuricza Laszlo says

    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

  17. Tom says

    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 says

      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.

  18. Zane DeVault says

    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!

  19. atiq says

    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

  20. atiq says

    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

  21. Marcel Tripoux says

    Hi! Great post!

    Is there a way to combine both option, in order to call related tags only in the current category ?

  22. Bambang says

    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 :)

  23. Alex says

    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.

  24. Mohammad says

    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

  25. Muthu says

    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

  26. WPBeginner Staff says

    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 says

      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=””>

    • Lacey Tech Solutions says

      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.

  27. Rachael says

    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?

  28. Mason Coulter says

    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!

  29. Tom K. says

    Hello , i want to ask , is there way to make , that related posts would be by category and tags in one place? Thanks.

  30. Jonathan says

    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?

  31. Miro says

    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

  32. Caleb says

    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 :)

Zostaw odpowiedź

Dziękujemy za pozostawienie komentarza. Pamiętaj, że wszystkie komentarze są moderowane zgodnie z naszymi polityka komentarzy, a Twój adres e-mail NIE zostanie opublikowany. NIE używaj słów kluczowych w polu nazwy. Przeprowadźmy osobistą i konstruktywną rozmowę.