Returning a random post with get_posts(); in Wordpress

Viewed 2015

I am currently trying to return one random post from a custom post type in Wordpress. Currently, all it returns is the last post posted within that custom post type. I am currently using this code to get the posts:

<?php $posts = get_posts(array('posts_per_page' => 1, 'order_by' => 'rand', 'order' => 'ASC', 'post_type' => 'call_to_action')); if( $posts ): ?>
  <?php foreach ( $posts as $post ) : setup_postdata( $post ); ?>
    // Some code
  <?php endforeach; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>
1 Answers

Change 'order_by' => 'rand' to 'orderby' => 'rand'

Related