I want to show different content on each page refresh. To accomplish this, I've used the PHP array_rand() function.

I fetched posts and stored content in a value using the below code. When I output the value before array_rand(), it is showing first post content but in array_rand() if I output the random functionality is working but showing some random number. I believe it's post count. The minimum num shown is 0 and max is 2 there are 3 posts.

Check this here and the code I used is.

    $args = array(
        'posts_per_page' => '-1',
        'order'=> 'ASC',
        'paged' => $paged,
        'post_type' => 'Didyouknows' 

    $loop = new WP_Query( $args );
    $posts = $loop->get_posts();

    foreach($posts as $post){
        //echo $loop->['ID'];

        $rval[]= $post->post_content;

        //echo $loop[post_content];

        $rand = array_rand($rval);
        //echo $rval[$rand[0]];
        //echo $rand;

<h2><?php echo $rand; ?></h2>

Where am I going wrong?

1 Answer 1


Getting a single random post would be far more efficient than getting all posts, then plucking a random post from the query. Here's an updated WP_Query instance using 'orderby' => rand:

$args = array( 
    'orderby' => 'rand',
    'posts_per_page' => '1',
    'paged' => $paged,
    'post_type' => 'Didyouknows', // Post type names should never use capital letters, btw 

$loop = new WP_Query( $args );

if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) { $loop->the_post(); ?>
        <h2><?php the_content(); ?></h2><?php

In your original code, you are seeing the values of 0, 1, and 2 which represent the possible keys for elements within your $rval array. You should move $rand = array_rand($rval); out of the foreach loop and do something like:

<h2><?php echo $rval[ $rand ]; ?></h2>

The fist solution using WP_Query and 'orderby' => 'rand' is preferable though.

  • Thanks for the code and thanks for the tip worked like a gem, but any idea why array_rand didn't work?
    – dh47
    Sep 19, 2016 at 6:04
  • You got it! Yeah, updated my answer to address that too. Please click accept if the issue has been resolved so that it's more clear to the next person that encounters the issue. Sep 19, 2016 at 6:11
  • 1
    Wow...!! Thanks even the array_rand working. Sure I will use first method, thanks again :)
    – dh47
    Sep 19, 2016 at 6:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.