WordPress Guy

WordPress Guy designs and develops WordPress themes and plugins. WordPress Guy teaches you WordPress stuff.

Ever wanted to have a “Random Post” link or button in your sidebar but you don’t know where to start? Well, today I’m going to show you how to do it.

The principles

As you may know already, WordPress posts are stored in a MySQL database. For us to obtain the URL to a random post from that database, we need to run a MySQL query. It’s pretty simple actually, thanks to WPDB, a built-in database class that comes with every WordPress install, we don’t need to bother about database names, passwords, connections and disconnections, etc. We just need to run the query and echo the result.

The MySQL query

Our database query needs to look inside the posts table and select one random post from the published posts. This is what the query looks like:

SELECT guid FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY RAND() LIMIT 1

Let me explain how exactly this MySQL query works:

  1. SELECT guid - Select just the guid column value, which is where the URL to the post is located.
  2. FROM wp_posts - From the posts table
  3. WHERE post_type = 'post' - Since attachments are also saved in the posts table, we need to specify that we just want posts
  4. AND post_status = 'publish' - We just want the published posts, not scheduled posts, not drafts
  5. ORDER BY rand() - Get them in random order
  6. LIMIT 1 - And get just one result

The PHP code

Now, let’s type the PHP code. As I said, we’re going to make it simple by using the WPDB class, which comes bundled into WordPress. This is our code:

<?php
$randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1");
echo '<a href="'.$randomPost.'">Random Post</a>';
?>

In the first line of the code, we’re running the database query using the WPDB get_var() function, and storing the result inside a $randomPost variable. Then, in the second line, we’re echoing the link, pointing to the URL stored in the $randomPost variable.

Note I’m using $wpdb->posts instead of wp_posts, that way, we make sure that we’re selecting the right table, since you could have changed the table prefix (which by default is ‘wp_’).

That’s it for today. I hope you enjoyed the mini-tutorial.

Join testking VCP-410 online training program to learn about wordpress themes and become master using testking 350-001 guide and testking 640-802 tutorials related to wp topics.

Comments

Your Comment