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,
$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: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()?