JohnRobertPett
JohnRobertPett

Reputation: 1183

Returning a random post with get_posts(); in Wordpress

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; ?>

Upvotes: 3

Views: 3334

Answers (1)

Mihai
Mihai

Reputation: 26784

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

Upvotes: 4

Related Questions