$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.'">随机文章</a>';
  • SELECT guid – Select just the guid column value, which is where the URL to the post is located.
  • FROM wp_posts – From the posts table
  • WHERE post_type = 'post' – Since attachments are also saved in the posts table, we need to specify that we just want posts
  • AND post_status = 'publish' – We just want the published posts, not scheduled posts, not drafts
  • ORDER BY rand() – Get them in random order
  • LIMIT 1 – And get just one resul
–> Make it simple by using the WPDB class, which comes bundled into WordPress.


(required. But it will not be published)