Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'd like to display the most two recent published sticky posts by modifying the primary loop. A simple affair with the following loop.

However, if I schedule a sticky post to be published in the future, the loop fails - only displaying one sticky post. It's like it can see that there is a new sticky post, but since it's scheduled it does not display. And then the loop thinks it's already displayed the two posts I requested. Any ideas?

/* Get all sticky posts */
    $sticky = get_option( 'sticky_posts' );

    /* Sort the stickies with the newest ones at the top */
    rsort( $sticky );

    /* Get the 2 newest stickies (change 2 for a different number) */
    $sticky = array_slice( $sticky, 0, 2 );

  /* Query sticky posts */
  query_posts( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );
  while (have_posts()) : the_post();
   the_title();
   the_excerpt(); 
  endwhile();

/* Continue with Page Template */
share|improve this question

1 Answer 1

The issue is that you limit query to the two possible posts, but by default it will ignore the future one (since that's the point of it not being published yet).

Also the ID order is not guaranteed to be same as date order. ID is reserved when post is first created but date it is published can be freely manipulated.

And query_posts() is evil and should not be used.

So your query should be something like this (not tested):

$sticky = new WP_Query( array(
    'post__in'            => get_option( 'sticky_posts' ),
    'posts_per_page'      => 2,
    'ignore_sticky_posts' => true,
    // date descending is default sort so we don't need it explicitly
) );

while ( $sticky->have_posts() ) : $sticky->the_post();
    the_title();
    the_excerpt();
endwhile;

wp_reset_postdata();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.