WordPress   

Shortcode to get related posts according to the current post category in WordPress

<?php 
add_shortcode( 'related_articles', 'related_articles_shortcode' );
function related_articles_shortcode( $atts ) {
ob_start();
?>

<div class="related-posts-wrap">
		<?php
			$args = array(
				'post_type' => 'post',
				'post_status' => 'publish',
				'posts_per_page' => 6,
				'category__in' => wp_get_post_categories(get_the_ID()),
				'post__not_in' => array(get_the_ID()),
			);
			$loop = new WP_Query($args);
			if ( $loop->have_posts() ) :
				while ( $loop->have_posts() ) : $loop->the_post(); ?>
					<div class="related-post-card">
						<div class="related-post-img">
							<?php echo get_the_post_thumbnail(); ?>
						</div>
						<div class="related-post-body">
							<h3 class="related-post-title"><a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a></h3>
							<div class="related-post-meta">
								<span class="related-post-date">
									<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/images/clock.svg">
									<?php echo get_the_date(); ?>
								</span>
								<span class="related-post-categories">
									<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/images/tag.svg">
									<?php 
									$categories = get_the_category();
									$separator = ' ';
									$output = '';
									if ( ! empty( $categories ) ) {
									foreach( $categories as $category ) {
										$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
									}
									echo trim( $output, $separator );
									}
									?>
								</span>
							</div>
							<div class="related-post-excerpt">
								<?php echo wp_trim_words( get_the_content(), 20, '...' ); ?>
							</div>
						</div>
					</div>
				<?php endwhile; 
				endif;
			wp_reset_postdata();
		?>
	
</div>

<?php
return  ob_get_clean();
}

In the frontend, it can be used as the following snippet

[related_articles]

 

Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us