pagination with sticky posts

The following code displays 8 posts on the 1st page. On all succeeding pages however, only 7 posts are displayed. I am assuming this is because the 1st page also displays sticky posts (whereelse the succeeding pages do not).

  • How can that problem be solved (I need 8 posts an all pages)?
  • Alternatively, the sticky posts should be displayed on all pages, not only on the first?

My original code:

$header_query = new WP_Query(
    'orderby=date&posts_per_page=7&paged='.$page_to_load.'&ignore_sticky_posts=0
');

EDIT: Implementation of Daniel Sachs’ suggestion:

// query db
$header_query1 = new WP_Query(
    array('post__in' => get_option('sticky_posts'), 'posts_per_page' => 1));
$header_query2 = new WP_Query(
    array( 'post__not_in' => get_option( 'sticky_posts' ), 'posts_per_page' => 7, 'orderby' => date, 'paged' => $page_to_load));

//display
getPostsFromQuery($header_query1);
getPostsFromQuery($header_query2);

function getPostsFromQuery($header_query) {
    if ( $header_query->have_posts() ) : 
    // loop etc.
}

I am still looking for a solution that requires only one database access? And for the alternative solution with sticky posts only on page 1.

1 Answer
1

I’d suggest using two queries, one for sticky posts, another for all the others.

First:

query_posts(array('post__in' => get_option('sticky_posts'), posts_per_page => 1));

then query all the other posts

query_posts( array( 'post__not_in' => get_option( 'sticky_posts' ), posts_per_page => 7, orderby => date, paged => '.$page_to_load.'));

this should do it.

Leave a Comment