WordPress related posts without plugin


If you are reading this post, then perhaps you are wondering how to display WordPress related posts with 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.

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.

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.

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


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.


Here you can check the latest resolved WordPress issues

Reported WordPress issues

  1. wordpress shipping cost reduction total cart price
  2. wc_get_product_ids_on_sale() …getting product on sale in WooCommerce
  3. Preserving custom pages via redirect
  4. Wordpress - get_template_part() section not showing
  5. Can't click behind my Iframe. Is it possible?
  6. To show toggle and simple menu
  7. Post in WordPress
  8. Get Json Data when a variable matches with ACF custom field in WooCommerce
  9. BuddyPress shared user-base on Multisite separate sites
  10. How to show product variation in cloumn instead of row in Wordpress?

WordPress problems we are working on

  1. All pages redirect to home page
  2. Is possible to read a value from a dynamic HTML table and pass it to an input form?
  3. Google Shopping With Multiple Titles
  4. Wordpress - white screen of death when trying to update a page and/or a file in Editor
  5. cart is not working with more than 3 variations Woocommeerce.?
  6. Apache set Access-Control-Allow-Origin from http to https
  7. Wordpress works fine on admin dashboard but not loading for public
  8. Tranform in ::before breaking child elements in Wordpress navigation menu - CHROME
  9. How to flash error message in wordpress?
  10. Warning: Illegal string offset while searching of product

Resolved issues

  1. How to edit this function to improve performance in Wordpress?
  2. Wordpress get post id
  3. Open Lightbox on onload page
  4. Blogs posts on an alternative page?
  5. Style don't change in form
  6. Using Consolibyte's PHP Devkit to Add a Customer to Quickbooks POS Desktop v.12 w/ Web Connector
  7. How to reset all fields when adding to WooCommerce Cart
  8. Wordpress Rest API and AngularJS ui-sref and custom HTML
  9. Importing contact form in front-page.php
  10. Wordpress - adding a custom font via font-face
wppotion - powered by persistence and passion