You May Also Like, filter snippet

“You May Also Like”, code snippet for displaying list of posts from the same category on page:

add_filter( 'the_content', function() {

	$id = get_the_id();

	if ( !is_singular( 'post' ) ) {
		return $content;
	}

	$terms = get_the_terms( $id, 'category' );
	$cats = array();

	foreach ($terms as $term) {
		$cats[] = $term->cat_ID;
	}

	$loop = new WP_Query (
		array(
				'posts_per_page' => 3, // Up to how many posts to display
				'category__in' => $cats,
				'order_by' => 'rand', // Random order of displayed posts
				'posts__not_in'	=> array($id) // Not showing the current post on the list
		)
	);

	if ( $loop->have_posts() ) {
		$content .= '
			<h2>You May Also Like:</h2>
			<ul class="you-may-also-like">
		';

		while ($loop->have_posts()) {
			$loop -> the_post();

			$content .= '
			<li>
				<a href="' . get_permalink() .'">' . get_the_title() . '</a>
			</li>';
		}

		$content .= '</ul>';

		wp_reset_query();
	}

	return $content;
});

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.