All Posts tagged : "code snippet"

wordpress_random_post

Get Random Post in WordPress

Here is the quick code snippet to get the random post from wordpress database. This can be usefult if you create “Random Post” link in your website and get random post for your readers.

I will get this done very quick here with just code block. I will explain the same task with two different ways:

Method 1: Using get_posts()

$args = array( 'numberposts' => 1, 'orderby' => 'rand' ); $random_post = get_posts ( $args ); // Your random post is ready now.
  $args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
  );
 
  $random_post = get_posts ( $args );
  // Your random post is ready now.

Method 2: Using WP_Query Object

$args = array( 'posts_per_page' => 1, 'orderby' => 'rand' ); $random_post = new WP_Query ( $args ); while ( $random_post->have_posts () ) { // traditional Wordpress Look }
  $args = array(
    'posts_per_page' => 1,
    'orderby' => 'rand'
  );
 
  $random_post = new WP_Query ( $args );
 
  while ( $random_post->have_posts () )
  {
    // traditional Wordpress Look
  }

There can be other severals ways to get this done, but I have explained which comes first to mind while writing this.

Subscribe to get latest updated right into your inbox, Follow us on twitter and Like us on facebook.