WordPress Wednesday: Displaying Random & Related Posts

Geek Factor: 3

In this week’s WordPress Wednesday, we’re going to cover two little code snippets that can encourage readers to check out other posts on your blog or site: one to display a list of related posts, and another to display a list of random posts.

Related Posts

To display a list of posts related to the one currently being displayed, you can query posts that share the same tag; in this example, we’re querying based on the current post’s first tag.

The below code comes from the WordPress Support Forums:

[php] ID); // the rest will only run if the current post has tags if ($tags) { // grab the first tag $first_tag = $tags[0]->term_id; // query posts with that tag, excluding the current one $relatedPosts = new WP_Query(array( 'tag__in' => array($first_tag), 'post__not_in' => array($post->ID), 'showposts'=>5, 'caller_get_posts'=>1 )); // run the loop if($relatedPosts->have_posts()) : ?>

Related Posts

    have_posts()) : $relatedPosts->the_post(); ?>

Random Posts

WordPress makes it quite simple to display a list of random posts by allowing queries to be ordered randomly — by creating a query of 5 posts and setting the orderby value to rand, you can potentially query any five posts from the site.

Note: If you are using this code on a single post page, remember to include 'post__not_in' => array($post->ID) in your query to exclude the current post from the results.

[php] 'rand', 'showposts' => 5)); if($randomPost->have_posts()) : ?>

More Posts

    have_posts()) : $randomPost->the_post(); ?>

What other ways do you encourage readers to check out other content on your site? Please share in the comments!

  1. Stephan said:


    many thanks for these little code snippets. But is it possible to have both?

    When you use the “Related Posts” snippet, the posts are always the 5 last posts of the site using the first tag. What I would like is to use a snippet capable of displaying five random posts from all the posts using the same first tag.

    Thank you for help.


    @ 10:43 am

Leave a Comment

Note: Fields marked with a * are required; email addresses are not published.

Legal FAQ Collections