Offset posts from random loop

Posted on 16th September, 2017 Leave a Comment

I recently created a post grid with 3 post loops of random posts, separated by a single meta field content after each iteration.

This is where wp_list_pluck came into its own. You use the previous query array to offset the random posts used in the previous loop.

to offset the previous posts include the post__not_in to the WP_Query array.

The first loop was a standard loop, but the second and third required the removal.
The first loop:

$first_grid_query = new WP_Query(
	array(
		'posts_per_page'=>2,
		'post_type' => 'casestudy',
		'orderby' => 'rand',
	)
);
while ($first_grid_query->have_posts()) : $first_grid_query->the_post(); 

The second itteration looked like this:

$first_grid_posts_ids = wp_list_pluck( $first_grid_query->posts, 'ID' ); 

$second_grid_query = new WP_Query(
	array(
		'posts_per_page'=>3,
		'post_type' => 'casestudy',
		'orderby' => 'rand',
		// Add the post ids from the first loop
		'post__not_in' => $first_grid_posts_ids,
	)
);
while ($second_grid_query->have_posts()) : $second_grid_query->the_post(); 

The second required an array merge, to include the first posts + second loops post.

// grab the IDs from the above query
$second_grid_posts_ids = wp_list_pluck( $second_grid_query->posts, 'ID' ); 
// Merge the 2 queries into a single array
$merged_post_id_arrays = array_merge($first_grid_posts_ids, $second_grid_posts_ids);

$third_grid_query = new WP_Query(
	array(
		'posts_per_page'=>1,
		'post_type' => 'casestudy',
		'orderby' => 'rand',
		// remove merged arrays from this loop
		'post__not_in' => $merged_post_id_arrays, 
	)
);

while ($third_grid_query->have_posts()) : $third_grid_query->the_post(); 

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]