The Simplest Way to Add Related Posts to Your WordPress Site Without Plugins

Creating your own Related posts for WordPress custom post types or for your blog isn’t that hard. You can use my example code below to set it up.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Before we start, I assume you already have experience with editing PHP and working with your WordPress child theme.

Also check the new post about adding related posts without plugins.

Okay, let’s get started. First we open our custom single post where we want to show our related posts. let’s say we have a custom post type tutorials and we want to create related posts for the related categories of tutorials.

First we need to add a new Query as below. Change 'post_type' to your custom post type slug or if it’s for your blog, you can use post. We also use 'post__not_in' to avoid our current post showing up as a related post.

$related = new WP_Query(
        array(
                'post_type'      => 'tutorials', //YOUR CPT SLUG
                'category__in'   => wp_get_post_categories( $post->ID ),
                'posts_per_page' => 3,
                'post__not_in'   => array( $post->ID ),
        )
);
Code language: PHP (php)

On the same single post page, we need to loop our existing posts and while there are posts, we show our custom related posts layout. Add the following code as below. We use our featured image as a background-image and use the wp_trim_words() function to trim our text from get_the_content().

if ( $related->have_posts() ) { ?>
<h3><?php _e( 'You might like this too!', 'hoolite' ); ?></h3>
	<div class="cpt-list">
		<?php
		while ( $related->have_posts() ) {
			$related->the_post();
			?>
			<div class="cpt-post">
				<div class="cpt-post--wrapper">
					<?php
					$featured_image = get_the_post_thumbnail_url( get_the_ID(), 'medium' ); // THUMBNAIL, MEDIUM, LARGE, FULL.
					$default_image  = get_site_url() . '/wp-content/uploads/2022/02/my_backup_image.jpg'; // URL TO YOUR DEFAULT/BACKUP IMAGE.
					$post_thumbnail = has_post_thumbnail( $post->ID ) ? $featured_image : $default_image; // CHECK IF FEATURED IMAGE ELSE USE DEFAULT IMAGE
					?>
					
					<a href="<?php echo esc_url( get_the_permalink() ); ?>" title="<?php echo esc_html( the_title() ); ?>">
						<div class="cpt-post--thumb" style="background-image: url('<?php echo $post_thumbnail; ?>')"></div>
					</a>

					<div class="cpt-post--text-inner">
						<a href="<?php echo esc_url( get_the_permalink() ); ?>" title="<?php echo esc_html( the_title() ); ?>"><h3><?php echo esc_html( get_the_title() ); ?></h3></a>
						<?php echo wp_trim_words( get_the_content(), 25 ); ?>
					</div>
				</div>
			</div>
			<?php
		}
		wp_reset_postdata();
		?>
	</div>
	<?php
} else {
	esc_html_e( 'Woops! Nothing found!', 'hoolite' );
}
Code language: PHP (php)

After that, you can add the following CSS and fine-tune it for your website usage. This is just a basic layout.

/* EXAMPLE CSS */
.cpt-list {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -16px;
}

.cpt-list .cpt-post {
    padding: 0 16px;
    margin-bottom: 32px;
    width: 33.33%;
}

.cpt-list .cpt-post .cpt-post--text-inner {
    padding: 16px;
}

.cpt-list .cpt-post .cpt-post--thumb {
    height: 200px;
    background-size: cover;
    background-position: center;
}

.cpt-list .cpt-post .cpt-post--wrapper{
	box-shadow: 4px 8px 40px 0 rgb(0 0 0 / 10%);
	height: 100%;
}
Code language: CSS (css)

That’s it! Creating related posts in WordPress without the use of plugins is a simple and efficient way to enhance the user experience on your website. By implementing this feature, you can boost user engagement, improve navigation and potentially increase your website’s SEO. The above tutorial provides a step-by-step guide on how to create related posts in WordPress through custom coding. Whether you are a beginner or an experienced developer, this guide can help you add this useful feature to your WordPress site without relying on third-party plugins.

You can download the demo files here on GitHub.

If you have any questions related to this post, let me know in the comment section below!

Leave your feedback and help us improve 🐶

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee ☕️ or donating via PayPal 💰.

More free knowledge, because why not?

5 Comments

  • Very nice info and right to the point. I am not sure if this is really the best place to ask but do you people have any ideea where to employ some professional writers? Thx 🙂

    Reply
  • It’s awesome in suppⲟrt of me to have a websіte,
    which is hеlpful for my experience. tһanks admin

    Reply
  • Hі there, You’ve done an excellеnt job. I will definitely diɡg it and
    ρersonally recommend to my fгiends. I’m confident they’ll be benefited from this website.

    Reply
  • I have not checked in here for some time as I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

    Reply
  • Pretty! This was an іncredibly ᴡonderful post. Thanks for supplying this info.

    Reply

Your thoughts matter, leave a reply 💬

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