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.

As part of my homepage template, using the standard query_posts I'm pulling out 1 post (styled using a different content_part), then an ad, then the rest of the posts. This works fine, except for when someone sets a post as sticky, when the loop with a posts_per_page set to 1, pulls out 2.

How can I get his loop to only ever show 1 post, either the latest, OR the top sticky, but not both (which I understand is the expected behaviour)? Currently I have:

    <?php 
$posts_per_page = get_option('posts_per_page');
$num_featured_posts = 1;

query_posts(array('posts_per_page' => $num_featured_posts)); ?>

  <?php if ( have_posts() ) : ?>

    <?php while ( have_posts() ) : the_post(); ?>

      <?php get_template_part( 'content', 'super' ); ?>

    <?php endwhile; ?>

  <?php elseif ( current_user_can( 'edit_posts' ) ) : ?>

    <?php get_template_part( 'no-results', 'index' ); ?>

  <?php endif; ?>

Thanks,

UPDATE: After explicitly calling out out only 1 post, regardless of sticky statuses, and exclusing that from the main loop of posts, my main loop now duplicates a post on subsequent pages (last one becomes first on page 2). Offset is causing me headaches and generally breaks pagination easily - is there another way to fix/add to this:

  wp_reset_query();
  $args = array(
    'post__not_in' => array($first_sticky_post),
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),        
  );
  //query_posts( $args );
  $main_loop = new WP_Query( $args );

... to reset where the loop should start on pages > 1?

You can see it in action here: n2.project14.co.uk

Thanks,

share|improve this question
    
Do not use query_posts to make queries or modify the main query. Either use WP_Query or hook into pre_get_posts –  Tom J Nowell Oct 7 '12 at 17:42

1 Answer 1

$GLOBALS['wp_query']->found_posts will give you the number of posts.

$GLOBALS['wp_query']->posts is an array with all the posts found.

So instead of while ( have_posts() ) : the_post(); use:

setup_postdata( $GLOBALS['wp_query']->posts[0] );
get_template_part( 'content', 'super' );

This way you don’t run through all post, you really just use one.

And please read When should you use WP_Query vs query_posts() vs get_posts()?

share|improve this answer
    
Thanks - that pointed me in the right direction for explicitly pulling out one post. That's added a minor problem with the main loop - post edited above to explain... –  Luc Pestille Oct 21 '12 at 19:54

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.