How to display related post by category

PHP Code Snippets/Functions

Requirements:

  • sample post
  • category

In this tutorial I will teach you how to display related post. Basically, this related post is post under the same category of the current post. This post is only applicable to put in a single post that has an assigned category else this will not function.

Step 1: create a dummy post(atleast 3 since our code below uses 3 sample post)
Step 2: Assign your post a category.
Step 3: Copy and paste the code below in your shortcode.php

<?php
function display_related_post_sc($atts, $content){
	extract( shortcode_atts( array(
	), $atts));

	ob_start();

		$category_detail=get_the_category(get_the_ID());//$post->ID
		$arr_stock = array();
		foreach($category_detail as $cd){

			array_push($arr_stock,$cd->term_id);
		}


		$args = array (
			'post_type' => 'post',
			'posts_per_page' => 3,
			'post__not_in' => array(get_the_ID()),
		    'cat' => $arr_stock
		);
		$the_query = new WP_Query( $args );

		?>
		<div class="related-post-container">
			<?php
			if ( $the_query->have_posts() ) {
				while ( $the_query->have_posts() ) {
					$the_query->the_post();
					$feat_img = get_the_post_thumbnail_url(get_the_ID());
					if(empty($feat_img)){
						$feat_img = "/wp-content/uploads/2023/09/MicrosoftTeams-image-2.png";
					}
					?>
						<div class="related-post-item">
							<img class="related-post-img" src="<?php echo $feat_img; ?>" width="100%" height="236px">
							<a href="<?php echo get_permalink(get_the_ID());?>" class="related-post-title"><?php echo get_the_title(); ?></a>
						</div>
					<?php
				}
			}
			?>
		</div>
		<?php
		// Restore original Post Data.
		wp_reset_postdata();

		return do_shortcode( ob_get_clean() );
	}
add_shortcode('display_related_post', 'display_related_post_sc');

?>

Step 4: In your single post template, or somewhere in your single post, put this code in your shortcode block “[display_related_post]”
Step 5: Save and check your single post to see of its working.

note: you can always modify the shortcode however you want.

That’s all for this tutorial, if you have any question contact the author of this post.

Leave a Reply

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