WordPress related posts without plugin


WordPress related posts basics

If you are reading this post, then perhaps you are wondering how to display WordPress related posts without a plugin. That task is actually not that hard to be accomplished. In the following guide I will show you two approaches to find and display related posts with just little pieces of custom code.

Before starting this training session, I would like to take a moment and explain that related articles are extremely useful for the visitors. This way they find more and valuable information. If the landing page offers related posts on the matter, then you are naturally increases the chances to lower the bounce rate and keep the visitors longer on your page.

Show wordpress related posts using a custom code

Displaying related posts without plugin keeps your WordPress clean of extra extensions and features that you may not want to use. The pieces of custom code I prepared for you do exactly what you need without any additional options or database queries that may slow down the overall performance of your website.

The first piece of code is designed for single or posts pages. It uses global variable $post and using wp_get_post_tags function gets post ID. Then based on the results it also gets tags based on certain parameters and finally loops through the results. Before proceeding however, I would like to provide more information on the preparations I did before applying my code:

  • I posted a few articles
  • I set tags to 3 of them
  • I checked my post ID. This could be done from wp-admin section -> Posts -> Tags -> Edit next to the Tags -> In the URL you will see a string that says tag_ID= and then a number. In my case this number is 16.
  • To check if my code is working fine I will use the following snippet:
echo '<pre>';

print_r($variabe);

echo '</pre>';

Its idea is to dump the information stored in the variable so that I can easily determine whether the code is getting and returning the information I need in order to display related posts.

Custom code – revision and explanation

Now let’s start with the code. Right after the PHP opening tag we define our post as equal to $post and also use the global variable. Then we add a new function $wppGetTags which is equal to wp_get_post_tags. It retrieves tags of a specific post. The whole information will be stored in $wppGetTags. Here is the first point where we can make a little test. If you add the following code:

echo '<pre>';

print_r($wppGetTags);

echo '</pre>';

after:

$wppGetTags = wp_get_post_tags($post->ID);

you will see the following output in your single or posts page:

WordPress related posts - data dump

WordPress related posts – data dump

As you can see the term_id is 16. Name and slug are mytag. Taxonomy and its ID are post_tag and again the number 16. Count is 3. This number comes from posts_per_page parameter which we passed to our args array and finally the filter is raw. If you see similar results on your page, then the test is passed successfully and we are ready to proceed further. Now let’s comment or remove these 3 additional lines and continue with our code.

So far we identified our post, its ID and tags. The 4th lines says if $wppGetTags returns some information go to the 5th line and define a new variable $tagIds which is equal to an array. That array contains foreach loop that loops through the results stored in $wppGetTags. We also pass arguments to it. We say, we want all tags related tags, that are not in this posts and we want the maximum number of the tags displayed to be 3. We also say caller_get_post equal to 1, because we do not want any sticky posts from being displayed first.

At this moment we have prepared our arguments and now we are ready to start looping through posts and display the titles of the related posts that are actually links to these posts. To do so we define a new variable $my_query which is a new instance of wp_query and pass our arguments to it. At the end we return $post and also reset our query with wp_reset_query(). This is important part as we do not want to mess with the standard WordPress query. If you miss to reset, then your WordPress instance may start acting strangely and return unpredictable results.

Custom code additions

Before checking the other approach I would like to say that I intentionally did not add fallback message for the first if statement. Let’s looks at line number 4. There we say if we have some information stored in $wppGetTags, then proceed with the code. Generally speaking it would be good to add else statement which would say something like “ There are no related posts”, but I skipped it as I do not want to see such message while working on my code. I however, will add it in the second piece of code.

<?php $orig_post = $post;

global $post;

$wppGetTags = wp_get_post_tags($post->ID);

      if ($wppGetTags) {

      $tagIds = array();

            foreach($wppGetTags as $related_tag) $tagIds[] = $related_tag->term_id;

                  $args=array(

                  'tag__in' => $tagIds,

                  'post__not_in' => array($post->ID),

                  'posts_per_page'=>3,  

                  'caller_get_posts'=>1

                  );

      $my_query = new wp_query( $args );

            if( $my_query->have_posts() ) {

                  while( $my_query->have_posts() ) {

      $my_query->the_post();

     

      ?><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>" style="padding-right: 5px"><?php the_title(); ?></a><?php


            }

      }    

}

$post = $orig_post;

wp_reset_query(); ?>

Here is the final result of this code. Note it should be added to single.php file:

Wordpress related posts on signle page

WordPress related posts on signle page

The second piece of code would also help you display wordpress related articles. It is however, designed to act differently. Instead of modifying single or posts files, we will work directly with functions.php. We will user action hook, execution point and again custom function to identify the related posts. Now let’s start with it.

The construction of the action hook is very simple. It says in the end of each loop trigger our custom function (custom_wpp_related_posts). The code of the function is also similar to the first piece of code. We again get post tags and loop through them. Our  arguments define the slug, number of posts and not it. As I already said, I do not want the current post to appear in the related posts, so I again added post not in to our array. After defining our arguments we define to if statements. We check if we have some data in wpp_related_posts variable and also check if the page we are on is singular. This second is an extra check because I do not want related posts to appear on category or archive pages.

To make the code a little bit more interesting we use setup_postdata for the formatting in our foreach loop. To avoid switch PHP and HTML we directly echo out out HTML code into PHP. For better control we also define class for our posts and also add else statement for the first if statement. It says No related posts were found and this is our fallback message if our code does not find any related articles. In the end we again reset our function. As we used setup_postdata, we do this with wp_reset_postdata. This way we can be sure that the WordPress functionality is kept intact.

add_action( 'loop_end', 'custom_wpp_related_posts' );

function custom_wpp_related_posts()

{

    global $post;

    $wpp_get_tags = wp_get_post_tags($post->ID);

  

    if ($wpp_get_tags) {

        foreach ($wpp_get_tags as $tag) {

            $wpp_tag_slug = $tag->slug . ',';

        }

                       

        $args = array('tag' => $wpp_tag_slug, 'numberposts' => 3, 'post__not_in' => array($post->ID));

      

        $wpp_related_posts = get_posts($args);

        if ($wpp_related_posts) {

       

        if ( is_singular() ) {

                       

                  echo '<p class="related-posts-header">Related Posts</p><ul id="mdwpbp-related-posts">';

            foreach ($wpp_related_posts as $post) {

                setup_postdata($post);

                echo '<li class="related-post"><a href="';

                the_permalink();

                echo '">';

                the_title();

                echo '</a></li>';

            }

            echo '</ul>';

        }

                       

       }

    }

            else {

                                   echo 'No related posts were found';

                        }

    wp_reset_postdata();

}

Here is the final result of the code added to functions.php file

Wordpress related posts with custom function

WordPress related posts with custom function

Summary
WordPress related posts - how to display similar content without plugin
Article Name
WordPress related posts - how to display similar content without plugin
Description
What are wordpress related posts and how to display similar posts without plugin. WordPress content basics. Custom code to detect related posts and detailed explanations
Author
Publisher Name
wppotion


  • 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.

  • Anonymous Said:
    Hey Mike,
    Thanks for getting in touch with us. To make sure that we are on the right track, could be please confirm if you followed the instructions in our article or you used some other extension ?

  • Do you want to share your opinion?

    Your email address will not be published. Required fields are marked *


    *

    We are not industry specific. We are WordPress specific. We work with everyone to help them find solutions with their troubles.
    If you show us the problem you are experiencing, we will show you how to fix it. It is that simple.


    Reported WordPress issues

    1. How to output custom the file field values on another page with the file download link
    2. Looking for the ability to authorize a credit collection/token on pre sale products
    3. How to automatically activate the plugin while wordpress first installation using docker
    4. How do I perform an IF/ELSE statement using data from a database on wordpress?
    5. How to check if a post or property has been viewed (on each session)
    6. wordpress How do I remove post_ID from user_meta array value
    7. Wordpress hooks working on dashboard but not on actual website
    8. Form echo is not applied of first item in a list
    9. How can I remove unwanted 1px space under navigation bar?
    10. slow down jump to anchor in divi theme

    WordPress problems we are working on

    1. Advice on resolving HTTP 500 on WP site?
    2. Copying plugins to base wordpress image, Plugins folders are visible in cmd but not visible in volume mount
    3. how to handel submitted gravity form which contains singel file
    4. How to rearrange WordPress REST API comments?
    5. how to select multi button at same time with different group? [on hold]
    6. WordPress add access for users to edit his comments
    7. Show directories and files in wordpress uploads folder
    8. Insert date and time to custom wordpress mysql table using input type date and input type time by php code
    9. Contact 7 form is causing error in my website afrter updated to the latest wordpress 5.0
    10. How to Add Javascript Code to Button to track the Clicks in Wordpress

    Resolved issues

    1. how to print a variable javascript in a onmousedown event?
    2. Contact form 7 WordPress plugin not showing sender email
    3. Does Wordpress list all pages for crawlers?
    4. How to update links on a WordPress website from Google Drive automatically after changing hosts?
    5. some product thumbnails doesn't show up
    6. How to keep the same page for different languages
    7. WordPress : Treat value in functions.php for all inner PHP files
    8. How to echo something after header tag (wordpress)?
    9. Error layout Elementor Wordpress (not load)
    10. APIProjectMapError when using WP Google Map plugin to display map
    wppotion - powered by persistence and passion