How to sort posts with the first 2 or 3 by latest, and the rest is random?

EDIT: Here is the correct answer…

<!-- RECENT BLOG POSTS -->
<?php
$recentargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_recent_posts,
    'orderby' => 'post_date',
    'order' => 'DESC'
);
$rec_arr_posts = new WP_Query( $recentargs );

if ( $rec_arr_posts->have_posts() ) :

    while ( $rec_arr_posts->have_posts() ) :
        $rec_arr_posts->the_post();
    ?>

        <?php get_the_post_thumbnail_url(); ?>
        <?php the_permalink(); ?>
        <?php the_title(); ?>
        <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>
<!-- END RECENT BLOG POSTS -->  

<!-- RECENT EXCLUDED POSTS -->
<?php
$recenttoexcludeargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_recent_posts,
    'orderby' => 'post_date',
    'order' => 'DESC'
);
$recent_to_exclude_arr_posts = new WP_Query( $recenttoexcludeargs );

if ( $recent_to_exclude_arr_posts->have_posts() ) {
    $posts_ids = wp_list_pluck( $recent_to_exclude_arr_posts->posts, 'ID' );
} ?>
<!-- END RECENT EXCLUDED POSTS -->
<!-- RANDOM BLOG POSTS -->
<?php
$randomargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_random_posts,
    'post__not_in' => $posts_ids,
    'orderby' => 'rand',
    'order' => 'DESC'
);
$rand_arr_posts = new WP_Query( $randomargs );

if ( $rand_arr_posts->have_posts() ) :

    while ( $rand_arr_posts->have_posts() ) :
        $rand_arr_posts->the_post();
    ?>

        <?php get_the_post_thumbnail_url(); ?>
        <?php the_permalink(); ?>
        <?php the_title(); ?>
        <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>

You need to set the variables $number_of_recent_posts & $number_of_random_posts.

P.S – where do you work? – I am coming for your job c:

Leave a Comment