Home » Add Related Posts In WordPress Without Plugin

Add Related Posts In WordPress Without Plugin

Last updated on December 27, 2020 by

Related posts could play a key role to boost your page views and reduce bounce rate. So here we will show you how to add related posts in WordPress without a plugin. Are you excited to do this? Let’s just jump into it.

Table of Contents
1. An Ideal Place to Add Code in WordPress
2. Get Related Posts by Category
3. Add Related Posts After Post Content in Single Post Page
4. Get Related Posts by Tags
5. Add Related Posts in a Custom Post Type by a Taxonomy
6. Automate Related Posts by Category or CPT’s Taxonomy

An Ideal Place to Add Code in WordPress

Most Important: Add the following code to your child theme’s functions.php file. If you add custom code directly to your parent theme’s functions.php file then it will be wiped entirely when you update the theme.

If you are using a custom theme and if it doesn’t require any update then you can directly place the code into wp-content/themes/your-theme/function.php file.

Please also note that our team has tested all codes in WordPress 5.4 version with the GeneratePress child theme & Storefront child theme.

01 Get Related Posts by Category

So here we will create a shortcode "[prefix_related_posts_for_single]" which then can be added anywhere you like.

/*@ Get Related Posts for Single Page */
if ( ! function_exists( 'sc_get_related_posts_for_single' ) ) {

    function sc_get_related_posts_for_single() {
        
        ob_start();

        $id = get_the_ID();  

        /*@ Get current post's categories */
        $categories = get_the_category($id); // Disabled this if you want tag wise posts 

        /*@ Get current post's Tags */
        // $categories = wp_get_post_tags($id); // Enable this for tags wise related posts


        if (!empty($categories)) :

            /*@ Pluck all categories Ids */
            $categories_ids = array_column( $categories, 'term_id' );

            $related_args = [
                'post_status'         => 'publish',
                'category__in'        => $categories_ids, // Disabled this if you want tag wise posts
                //'tag__in'        => $categories_ids, // Enable this for tag wise related posts
                'post__not_in'        => [ $id ], // Exclude Current Post
                'posts_per_page'      => 4, // Number of related posts to show
                'ignore_sticky_posts' => 1
            ];

            $get_posts = new WP_Query( $related_args );

            if ( $get_posts->have_posts() ) :

            	echo '<div style="clear:both;"> </div>';
	                echo '<div class="related-section-wrapper">';

	                    echo '<div class="section-title"><h4>Related Posts</h4></div>';

	                    echo '<div id="columns"><ul class="related-posts-wrapper">';

	                    while ( $get_posts->have_posts() ) : $get_posts->the_post();

	                        echo '<li><a href="'.get_the_permalink().'"><div class="related-post-thumb">'.get_the_post_thumbnail().'</div><div class="related-post-title">'.get_the_title().'</div></a></li>';
	                    endwhile;

	                    echo '</ul></div>';
	                    
	                echo '</div>';
                echo '<div style="clear:both;"> </div>';

            endif;
          
        endif; 

        return ob_get_clean(); 

    }
    add_shortcode('prefix_related_posts_for_single', 'sc_get_related_posts_for_single');
}

The above code will find out the current Post ID and get all categories associated with it. After that, we plucked the IDs of all categories. All those categories IDs passed in "category__in" argument. Then, we are fetching posts with the help of WP_Query() function.

Currently, We are showing 5 related posts, so if you want to show more or fewer posts then you need to change the 'posts_per_page' => 5, argument.

Add Related Posts After Post Content in Single Post Page

Following code will place the related posts after the post content and before the comment form.

function sc_add_related_post_in_single( $content ) {    

    if( is_single() ) :
        $content .= do_shortcode('[prefix_related_posts_for_single]');
    endif;

    return $content;
}
add_filter( 'the_content', 'sc_add_related_post_in_single' );

On the above example, We are appending our related post right after the post content on a single page. Filter hook provides a way to append or modify the data so we have used “the_content” filter hook for that purpose.

The $content variable has all the current post content in it. Then we added a condition to check if the current page is a single page or not. If the current page is a single page, then we are calling our related post shortcode with the help of do_shortcode() function and appended into a $content variable with the help of .= operator (Concatenation assignment). We hope you understood the use of the above example.

Now, It’s time to add some CSS as below. Please note that the look will vary as per your theme. You might need to add/change some CSS as per your requirement.


/*@ Related post single */

.related-section-wrapper {
	display: block;
	float: left;
	background-color: #FFF;
	padding: 10px;
	box-sizing: border-box;
	width: 100%;
}

.related-section-wrapper #columns {
	-moz-column-count: 2;
	-moz-column-gap: 20px;
	-webkit-column-count: 2;
	-webkit-column-gap: 20px;
	column-count: 2;
	column-gap: 20px;
}

.related-section-wrapper .related-posts-wrapper {
	list-style: none;
	margin: 0px auto;
}

.related-posts-wrapper li {
	display: inline-block;
	box-sizing: border-box;
	box-shadow: 0 0px 10px #d8e2f3;
	font-weight: 500;
	border-radius: 5px;
	transition: all .2s;
	border-radius: 0px;
	margin-bottom: 40px;
}

.related-posts-wrapper li a {
	text-decoration: none !important;
	padding: 0px !important;
	padding-bottom: 0px !important;
	box-shadow: none !important;
	padding-bottom: 0px !important;
	color: #000 !important;
}

.related-posts-wrapper li:hover {
	box-shadow: 0 3px 5px #d8e2f3;
	transform: translateY(-2px);
}

.related-posts-wrapper .related-post-thumb {
	height: 200px;
	overflow: hidden;
	vertical-align: middle;
	display: inline-block;
}

.related-posts-wrapper .related-post-thumb img {
	border-radius: 0px;
}

.related-posts-wrapper .attachment-post-thumbnail {
	height: 100%;
}

.related-posts-wrapper .related-post-title {
	padding: 10px;
	min-height: 110px;
	font-family: "Bree Serif", serif;
	font-weight: 600;
	font-size: 20px;
}


/*@ Reponsive Style */


/* @Device: Most of the Smartphones Mobiles (Portrait) */

@media (min-width: 320px) and (max-width: 480px) {
	.related-section-wrapper #columns {
		-moz-column-count: 1;
		-moz-column-gap: 0px;
		-webkit-column-count: 1;
		-webkit-column-gap: 0px;
		column-count: 1;
		column-gap: 0px;
	}
}


We have already placed the code in a comment on above the example, If you want to enable related posts Tag wise, then you need to disable the Category wise code and enable Tag wise code.

You just need to comment or replace this $categories = get_the_category($id); to $categories = wp_get_post_tags($id); and this 'category__in' => $categories_ids, to 'tag__in' => $categories_ids, on the above example. After that, your code should look like below.

/*@ Get Related Posts for Single Page */
if ( ! function_exists( 'sc_get_related_posts_for_single' ) ) {

    function sc_get_related_posts_for_single() {
        
        ob_start();

        $id = get_the_ID();  

        /*@ Get current post's categories */
        //$categories = get_the_category($id); // Disabled this if you want tag wise posts 

        /*@ Get current post's Tags */
         $categories = wp_get_post_tags($id); // Enable this for tags wise related posts


        if (!empty($categories)) :

            /*@ Pluck all categories Ids */
            $categories_ids = array_column( $categories, 'term_id' );

            $related_args = [
                'post_status'         => 'publish',
                //'category__in'        => $categories_ids, // Disabled this if you want tag wise posts
                'tag__in'        => $categories_ids, // Enable this for tag wise related posts
                'post__not_in'        => [ $id ], // Exclude Current Post
                'posts_per_page'      => 4, // Number of related posts to show
                'ignore_sticky_posts' => 1
            ];

            $get_posts = new WP_Query( $related_args );

            if ( $get_posts->have_posts() ) :

            	echo '<div style="clear:both;"> </div>';
	                echo '<div class="related-section-wrapper">';

	                    echo '<div class="section-title"><h4>Related Posts</h4></div>';

	                    echo '<div id="columns"><ul class="related-posts-wrapper">';

	                    while ( $get_posts->have_posts() ) : $get_posts->the_post();

	                        echo '<li><a href="'.get_the_permalink().'"><div class="related-post-thumb">'.get_the_post_thumbnail().'</div><div class="related-post-title">'.get_the_title().'</div></a></li>';
	                    endwhile;

	                    echo '</ul></div>';
	                    
	                echo '</div>';
                echo '<div style="clear:both;"> </div>';

            endif;
          
        endif; 

        return ob_get_clean(); 

    }
    add_shortcode('prefix_related_posts_for_single', 'sc_get_related_posts_for_single');
}

On the above example, We have used wp_get_post_tags() function to fetch all the tags related to the current post, then we plucked the tags IDs and passed those IDs to tag__in argument, tag___in will find out the posts related to the current post’s tags. We hope you understood this. Let’s see some further topics.

Up till now, We have seen the related posts by category & tags, but what about a Custom Post Type taxonomy. It’s not that much harder. So to display related posts in a Custom Post Type, we will create another shortcode "tf_cpt_related_posts".

/*@ Get Related Posts for Custom Post Type */
if ( ! function_exists( 'tf_get_related_posts_for_cpt' ) ) {

    function tf_get_related_posts_for_cpt() {
        
        ob_start();

        $id = get_the_ID();  

        /*@ Get current post's Taxonomy */
        $taxonomy_terms = wp_get_post_terms($id, 'glossary');  // Replace your taxonomy name

        if (!empty($taxonomy_terms)) :

            /*@ Pluck all terms Ids */
            $terms_ids = array_column( $taxonomy_terms, 'term_id' );

            $related_args = [
            	'post_type' => 'source-book',  // Replace your post type name
            	'tax_query' => [
                [
                    'taxonomy' => 'glossary', // Replace your taxonomy name
                    'field'    => 'id',
                    'terms'    => $terms_ids,
                    'operator' => 'IN' // Options : 'AND' or 'NOT IN'
                ]],
                'post_status'         => 'publish',
                'post__not_in'        => [ $id ], // Exclude Current Post
                'posts_per_page'      => 5, // Number of related posts to show
                'ignore_sticky_posts' => 1
            ];

            $get_posts = new WP_Query( $related_args );

            if ( $get_posts->have_posts() ) :

                echo '<ul class="related_posts_list">';

                while ( $get_posts->have_posts() ) : $get_posts->the_post();

                    echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
                endwhile;

                echo '</ul>';

            endif;
          
        endif; 

        return ob_get_clean(); 

    }
    add_shortcode('tf_cpt_related_posts', 'tf_get_related_posts_for_cpt');
}

On the above example, We have used wp_get_post_terms() function to fetch all the taxonomies related to the current post, then we plucked the taxonomies IDs and passed those IDs to tax_query argument.

In order to make the above example work, you need to change the taxonomy “glossary” at two places 1) 'taxonomy' => 'glossary' 2) $taxonomy_terms = wp_get_post_terms($id, 'glossary'); to your and change the 'post_type' => 'source-book' to your own, We hope you understood this. Let’s see some further topics.

We can show the related posts easily based on the condition to automate it. So if we are on default posts, then it will show the related posts based on the Categories and if we are on Custom Post Type posts, then it will show the related posts based on Taxonomy.

This example is just a mixture of the above code with some additional conditions. Here we will create a shortcode "[tf_related_posts]". Are you ready to do that? Let’s go then.

/*@ Get Related Posts */
if ( ! function_exists( 'tf_get_related_posts' ) ) {

    function tf_get_related_posts() {
        
        ob_start();

        $id = get_the_ID();  

        /*@ Get current post's categories */
        $categories = get_the_category($id);

        if ( get_post_type() === 'source-book' ) :
        	$categories = wp_get_post_terms($id, 'glossary'); // Replace your CPT Taxonomy
    	endif;

        if ( !empty($categories) ) :

            /*@ Pluck all categories Ids */
            $categories_ids = array_column( $categories, 'term_id' );

            $related_args = [
                'post_status'         => 'publish',
                'category__in'        => $categories_ids,
                'post__not_in'        => [ $id ], // Exclude Current Post
                'posts_per_page'      => 5, // Number of related posts to show
                'ignore_sticky_posts' => 1
            ];

            /*@ Show CPT related posts */
            if ( get_post_type() === 'source-book' ) : // Replace your post type
        			
        		unset($related_args['category__in']);

        		$related_args['post_type'] = 'source-book'; // Replace your post type
        		
        		$related_args['tax_query'] = [[
                    'taxonomy' => 'glossary', // Replace your CPT taxonomy name
                    'field'    => 'id',
                    'terms'    => $categories_ids,
                    'operator' => 'IN' // Options : 'AND' or 'NOT IN'
                ]];

    		endif;

            $get_posts = new WP_Query( $related_args );

            if ( $get_posts->have_posts() ) :

                echo '<ul class="related_posts_list">';

                while ( $get_posts->have_posts() ) : $get_posts->the_post();

                    echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
                endwhile;

                echo '</ul>';

            endif;
          
        endif; 

        return ob_get_clean(); 

    }
    add_shortcode('related_posts', 'tf_get_related_posts');
}

In order to make the above example work, You need to change the taxonomy and Custom Post Type name as we have shown in point 03.

We have added comments in the code wherever replacement requirement from your side so it will easy for you to replace the names. Please test all the examples one by one because all the above examples have the same function name so only first will execute.

Additionally, check out our guide: Add Related Posts Without Plugin in WordPress for Sidebar

That’s it for now. We hope this article helped you to add related posts in WordPress without a plugin.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂

 
 

Leave a Comment

*

code