WordPress related posts and custom post types loop

This WordPress loop will show related posts based on the current posts categories. It will include custom post types and exclude the current post and any duplicates.

It is intended to be placed outside the main loop on a single.php page.

The following are the steps I took to make the above loop:

There are several issues I had to solve:

Get the current posts categories and show posts in these categories

Using the wp_get_post_categories I assigned the array of category IDs to the var $post_categories

$post_categories = wp_get_post_categories( $post->ID );

You can print the values of the array to see if they are correct:


Then in the loop we select to only show post in these categories using category__in.

'category__in' => $post_categories,

Do not show duplicate if a post is in two of the categories

Thanks to Frank at wpengineer for help with this bit.  (http://wpengineer.com/1719/filter-duplicate-posts-in-the-loop/)

Using an array to store post IDs

$do_not_duplicate = array();

And an IF statement in the loop

if ( !in_array( $post->ID, $do_not_duplicate ) ) {
$do_not_duplicate[] = $post->ID;
// title and excerpt go here

Do not show the current post in the related posts loop

Get the current posts ID and assign it to a var.

$exclude_post = $post->ID;

Using post__not_in to exclude the current post using its ID in the loop args array.

'post__not_in' => array($exclude_post),

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s