Support » Fixing WordPress » post count mismatch between multiple loops

  • In the page layout I return 5 of the most recent posts (from any category except stickys) at the top of page – as loop 1.

    <?php
    global $post;
    $myposts = get_posts('category=-190&numberposts=5');
    foreach($myposts as $post) : setup_postdata($post);
    $do_not_duplicate[] = $post->ID; ?>
    <!-- doing stuff for 5 of most recent posts from all categories except stickys -->
    <?php endforeach; ?>

    Further down in the page I break out the categories separately and want to display the 5 most recent posts for each category (without duplicating the posts in loop 1).. call them loop 2, 3, 4 and 5 – but I will just use one of them since the changes would apply to all once it’s working – at least I hope.

    <?php
    $standargs = array( 'posts_per_page' => 5, 'category' => 191 );
    $standposts = get_posts( $standargs );
    foreach ( $standposts as $post ) : setup_postdata( $post ); if ( in_array( $post->ID, $do_not_duplicate ) ) continue;
    ?>
    <!-- just supposed to return 5 total posts in this single category -->
    <?php endforeach;
    wp_reset_postdata();?>

    I can successfully (relatively anyway) do this except one issue somewhere in the code that I cannot seem to figure out where the posts_per_page, or showposts, etc are mismatching between the 2 loops.

    For instance: if in loop 1 there are 2 articles for category 191, in the section lower in the page, loop 2 would only show 3 posts even though there are numerous other ones. I am fairly certain I am using posts_per_page wrong somehow. I’ve substituted posts_per_page with showposts and numberposts, it all does the same count issue where it will only show 5 total posts from that category in the entire page. I cannot use offset either because I cannot guarantee how many posts from a given category would show up in loop 1 and I need to have loop 2 show a definitive number of 5 posts from that category.
    PS feel free to correct me on my other coding issues as well LOL.

Viewing 1 replies (of 1 total)
  • use $do_not_duplicate with the 'post__not_in' parameter — see http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action after the headline ‘Note for Multiple Posts in the First Category

    Alternatively you can pass the entire $do_not_duplicate array to $wp_query and only entries that match your criteria will be returned:

    <?php query_posts( array( 'post__not_in' => $do_not_duplicate ) );
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    should also work accordingly with ‘get_posts()’

Viewing 1 replies (of 1 total)
  • The topic ‘post count mismatch between multiple loops’ is closed to new replies.