WordPress: Exclude Current Post When listing Random Posts

There may be an instance where you want to list random posts on a post page, this would usually be done in single.php or your sidebar. If you are listing random posts to try and keep people on your site, one thing that you are going to want to do is to exclude the current post. This is very easy to achieve using a WordPress custom query as follows…

<?php
	$currentID = get_the_ID();
	$recent = new WP_Query( 'exclude=' . $currentID . '&cat=10&showposts=5&orderby=rand' );
	while ($recent->have_posts()) : $recent->the_post();
?>
	// Your post titles etc. here
<?php endwhile; ?>

So let’s explain the code…

The first line ($currentID = get_the_ID();) gets the current page ID and puts it into a variable called $currentID.

The next line is the custom query which tells the query to exclude a post with the ID set by $currentID. The rest of the query is not needed, but we left it in to give you the option to customise your query further.

&cat=10 tells the query to only include posts from the category with the ID of 10.

&showposts=5 tells the query to only show 5 posts, you can set this to whatever number you want or to -1 if you don’t want it to have a limit.

Finally, &orderby=rand is the order that the posts are displayed in. As you can see the order is random, so will be different every time. There are many different ways you can order a custom query, more information can be found here.

That’s pretty much it! You now know how to create a custom query to display random posts on a post page excluding the current post.

Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358