How to show random posts after current post

March 23rd, 2009 Posted in Wordpress, Wordpress MU

Difficulty Level:


It is very useful to show some random posts after the current reading post. You online need one litle function for that:

  1. function get_random_posts ($number_of_posts) {
  2. global $wpdb, $post;
  3. $current_post = get_the_title();
  4. $random_posts = $wpdb->get_results("SELECT $wpdb->posts.ID, \
  5. post_title, post_name, post_date, post_type, post_status FROM \
  6. $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' \
  7. AND post_title != '$current_post' ORDER BY RAND() limit \
  8. $number_of_posts");
  9. foreach ($random_posts as $post) {
  10. $post_title = htmlspecialchars(stripslashes($post->post_title));
  11. echo "<li><a href=\"".get_permalink()."\">$post_title</a></li>";
  12. }
  13. }

How this works?

  1. Get the current post title with “$current_post = get_the_title();” because, we won’t show this title again
  2. Get x random posts “…$random_posts = $wpdb->get_results…”
  3. Go trought each post, get its title and show it “foreach ($random_posts as $post)…”

That’s all! Have Fun!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • StumbleUpon
  • Reddit

Comments are closed.

My-Guide Interessante Guides: MontenegroSport GuideGitte kochtYou must be jok..LaTeX