Home > OS >  How to get random 5 posts from latest 10 wordpress?
How to get random 5 posts from latest 10 wordpress?

Time:09-09

I'm trying to get 5 random posts from latest 10 but I get only last 5 in random order

My code is:

    $args = array(
        'numberposts' => 10,
        'offset'      => 0,
        'post_type'   => job_listing,
        'orderby'     => 'post_date',
        'order'       => 'DESC',
        'posts_per_page' => 5,
        'post_status' => 'publish'
    );

    $Latest = wp_get_recent_posts( $args, ARRAY_A );
    shuffle($Latest);

    return $Latest;

Am I missing something that doesn't give me random posts from the last 10, but just a random order from the last 5?

Thank you,

CodePudding user response:

Set

'posts_per_page' => 10,

change return in

return array_slice($Latest, 0, 5); 

CodePudding user response:

You got only last 5 in order because posts_per_page = 5.

try to change it like this

posts_per_page => 10

Instead of use shuffle, see the following code, You'll get 5 random from latest 10.

  $args = array(
        'numberposts' => 10,
        'offset'      => 0,
        'post_type'   => job_listing,
        'orderby'     => 'post_date',
        'order'       => 'DESC',
        'posts_per_page' => 10,
        'post_status' => 'publish'
    );

    $Latest = wp_get_recent_posts( $args, ARRAY_A );

    $new_array_latest = [];
    do {
       $new_array_latest[] = $Latest[array_rand($Latest ,1)];
    }while(count(array_unique($new_array_latest)) < 5);


    return array_unique($new_array_latest);
  • Related