Find n number of posts randomly from a group of categories in WordPress

tumblr_n2hutxfrNr1tubinno1_1280

When you are developing a theme, or maybe writing a plugin, it is often required to display related posts in single posts page. These related posts are fetched by various criteria. Sometimes they are fetched from the same categories a post belongs to, or by tags. Sometimes they are set by the author of the posts.

In this article I am going to show you how to fetch the categories of a particular post, and then fetch some random posts from these categories. It’s not as tough as you’re thinking.

Fetch the categories of a post
You can quickly fetch the categories assigned to a particular post using get_the_category() function. Let’s have a look at the following code block

[sourcecode language=”php”]
$post_id = 1234;
$categories = array();
$_categories = get_the_category($post_id);
foreach ($_categories as $_cat) {
$categories[] = $_cat->term_id;
}
[/sourcecode]

Now you have the array of category ids which are assigned to a particular post with post id “1234”.

Fetch posts from these same categories
Now we are going to fetch some posts from these categories fetched in step 1. We will use kinda less documented category__in and post__not_in parameters with get_posts() function. We will make sure that the post “1234” doesn’t come in the list of random posts. Because it will be silly to display that same post as a relative.

[sourcecode language=”php”]
$args = array(
‘orderby’ => ‘rand’, //important to fetch random posts
‘post_type’ => ‘post’,
‘numberposts’ => 3,
‘post__not_in’ => array($post_id), //exclude the same post
‘category__in’ => $categories,
‘post_status’=>’publish’
);
$related_posts = get_posts($args);
[/sourcecode]

Now you have an array of 3 related posts, which are related to the post “1234” by belonging in the same categories. Their properties are described in details here in this Codex Article

That was easy, wasn’t it? Hopefully you will find it useful in your next WordPress theme project. Good night.