Developer // WordPress Query For Showing Different Number of Posts on Different Pages

Working on a new project and the client wanted to show a different number of posts displayed on the first page of posts, than on the rest. In order to enable promoted cards to be given more prominence on the first page.

After googling I found a solution from Birgire which I adjusted to fit with my promoted cards.

It consists of setting variables for how many posts to display on first page and other pages, then using these numbers to calculate the offset for the query based on the users current page.

I’ve left in the code that displays the promoted cards in their relevant positions to give the full picture of what the code does.
// Display latest Study Days cards, including 2 featured cards on first page of results.
// Variables to handle the query for differing number of cards displayed on pages
$cardCount = 0;
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$pp_fp = 9 - $countPromoted; // posts per first page (depends on how many Promo Cards selected)
$pp_op = 9; // posts per other pages
$offset_fp = 0; // offset for the first page

// Offset for other pages than the first page
$offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;

// Set offset depending on current page
$offset = ( get_query_var('paged') ) ? $offset_op : $offset_fp ;

// Set posts per page depending on current page
$posts_per_page = ( get_query_var('paged') ) ? $pp_op : $pp_fp ;

$args = array(
'post_type' => 'study_days',
'posts_per_page' => $posts_per_page,
'post_status' => 'publish',
'order_by' => 'post_date',
'order' => 'DESC',
'paged' => $paged,
'offset' => $offset,
'post__not_in' => array($promotedCard1, $promotedCard2) //don't return promoted cards in results
);
$loop = new WP_Query( $args );

if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
// Output Promoted Cards at set positions
$cardCount++;
if($cardCount === 3 && $promotedCard1 != '') {
displayCard($promotedCard1, $promotedCard->post_type, true);
$cardCount++;
}
if($cardCount === 7 && $promotedCard2 != '') {
displayCard($promotedCard2, $promotedCard->post_type, true);
$cardCount++;
}
//Output regular card
$postID = get_the_ID();
displayCard($postID, 'study_days');
endwhile;
}

Leave a Reply

Your email address will not be published. Required fields are marked *