Php
Wordpress

Easy code for Related Posts in wordpress without plugin

Beginner 15 mintues
view more posts

As the name suggest this tutorial show you an easy code to display the related posts under single posts in wordpress. In this tutorial we make it expandable with custom post types and custom taxonomies in wordpress. There are no hacks or actions hooks involved in this code. It is very clean and uses the normal wordpress query. So you can also limit the number of related posts to be displayed in you website.

Consider you have a wordpress installation with a few custom post types. So naturally you would have used individual single-postType.php pages to display its contents. First I will explain you to use this code with individual single pages and then explain you how functions.php can be used to minimize the amount of codes written.

Variable that we need?

Like I said before we will be using wordpress query to fetch the related posts. Lets take a look at the code below to see what are the list of variables are required for the query.

<?php
$args = array(
    'post_type'=> array($postType),// ENTER THE POST TYPE TO QUERY HERE.
    'showposts' => $numPosts,
    $taxonomy => $term_slug,
    'orderby' => 'rand',
    'post__not_in' => array($excludeID),
);
query_posts( $args );
?>
So here is the list of things we need based on the code above:
  1. First we need the custom post type ($postType) of the article in which this code is place.
  2. The number of posts to be shown ($numPosts).
  3. Custom taxonomy ($taxonomy) and its term slug ($term_slug).
  4. And finally the ID of the current post to be excluded from the query.

How to fetch these variables?

All the variables can be fetched by the following code if and only if placed inside the worpdress loop of the single page post. The code shown below are pretty much self explanatory. So just copy them and make sure you past it inside the wordpress loop.

An example of the wordpress loop:

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> ?>
     //DISPLAY POSTS HERE
<?php endwhile;?>

Code to fetch the variables:

$exclude_postID = $post->ID;
$postType = get_post_type();
$taxonomy = 'taxonomy-name';
$numPosts = 3;
$terms = get_the_terms( $post->ID, $taxonomy);
if ( $terms && ! is_wp_error( $terms ) ) {
    $term_slug = array();
    foreach ( $terms as $term ) {
        $term_slug[] = $term->slug;
    }
    $term_slug = join( ", ", $term_slug );
}

We enter the value of $taxonomy variable directly as we know what taxonomy the post belongs to. Then using this value we get the $terms_slug variable using the get_the_terms() function. We also enter the $numPosts variable directly as we know how many posts to display.

Now the query & display of the posts.

Now that we have all the variables for a successful query we query the posts and using the wordpress loop and display it.

<?php
$args = array(
        'post_type'=> array($postType),// ENTER THE POST TYPE TO QUERY HERE.
        'showposts' => $numPosts,
        $taxonomy => $term_slug,
        'orderby' => 'rand',
        'post__not_in' => array($excludeID),
    );
    query_posts( $args );
   
if(have_posts()) { ?>

    <div class="read_more">
        <h2>Read More</h2>
        <ul>
            <?php
                while ( have_posts() ) : the_post(); ?>
                    <li>
                        <a href="<?php the_permalink(); ?>">
                            <?php the_post_thumbnail('thumbnail'); ?>
                        </a>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
            <?php endwhile;?>
        </ul>
    </div> <!-- END read_more -->

<?php }//END if have_post() ?>

After querying for the post we check if any post has been returned using if(have_posts()) condition. If it returns true then we run the loop and display the posts. You can follow any HTML structure you want to display the posts.

How to make it dynamic using functions.php

We create a function named related_posts() in functions.php and paste the query and loop code we discussed above into it. This function will have all the variable passed into it like below:

<?php
function related_posts($postType, $taxonomy, $term_slug, $numPosts, $excludeID) {
        $args = array(
            'post_type'=> array($postType),// ENTER THE POST TYPE TO QUERY HERE.
            'showposts' => $numPosts,
            $taxonomy => $term_slug,
            'orderby' => 'rand',
            'post__not_in' => array($excludeID),
        );
        query_posts( $args );
       
    if(have_posts()) { ?>

        <a name="more"></a>
       
        <div class="read_more">
           
            <h2>Read More</h2>
               
            <ul>
                <?php
                    if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
                        <li>
                            <a href="<?php the_permalink(); ?>">
                                <?php the_post_thumbnail('thumbnail'); ?>
                            </a>
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </li>
                <?php endwhile;?>
            </ul>
           
        </div> <!-- END read_more -->
   
    <?php }//END if have_post()
   
} //END read_more()

We basically encapsulate the query and wordpress lopp code inside a function. This is all that you have to paste in the functions.php file.

And only the following goes into the single php page.

Now that the variables are passed in the function itself it becomes dynamic. Now you can simply fetch these variables and pass it into your fucntion. So all that you have to do is paste the following in single php.

<?php
    $postType = get_post_type();
    $numPosts = 3;
    $excludeID = $exclude_postID;
    read_more($postType, $taxonomy, $term_slug, $numPosts, $excludeID);
    wp_reset_query();
?>

And yes! Ofcourse to fetch these variables like said before you have to paste them inside the query. Later outside the loop we assign them to the function.

Conclusion

You can see the demo working below this post itself. Each single page for the custom post types like trailer, tutos and movie reviews have their own Related Posts.

Please do ask if you have any doubts and help yourself with this very easy related posts code for wordpress.

Latest Comments

Leave a Reply

comment on this article