• I’m having a serious problem with do_not_duplicate and multiple loops.

    I’d like the first three loops to each show one post. Then, I’d like the fourth loop to show the remaining posts left in the main query (if admin read is set to 10, then loop four should show 7 posts) – avoiding duplication of the 3 posts above.

    For some strange reason, the do_not_duplicate IDs are not being stored in the second and third loop arrays – so the loop 1 is showing 1 post, and loop 4 is showing 9 posts. Essentially, loops 2 and 3 are being completely ignored.

    I cannot for the life of me figure out why. Can someone please help? Thank you!

    Note: Here is the full code in pastebin: https://pastebin.com/57KCEpxK

    <?php get_header(); ?>

    <h1>Loop 1</h1>
    <?php $do_not_duplicate = array();
    $my_query = new WP_Query(array('posts_per_page' => 1, 'post__not_in' => get_option( 'sticky_posts' ) ) );
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate[]  = $post->ID; ?>
    <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
    <h1>Loop 2</h1>
    <?php
     $args=array(
          'posts_per_page' => 1,
          'post__not_in' => $do_not_duplicate,
          'category__in' => array($category->term_id)
    );
    $my_query = new WP_Query( $args );
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate[] = $post->ID; ?>
    <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
    <h1>Loop 3</h1>
    <?php $args=array(
          'posts_per_page' => 1,
          'post__not_in' => array_merge($do_not_duplicate, get_option( 'sticky_posts' )),
          'category__in' => array($category->term_id)
    );
    $my_query = new WP_Query( $args );
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate[] = $post->ID; ?>
    <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
    <h1>Loop 4 (leftovers)</h1>
    <?php if (have_posts()) : while (have_posts()) : the_post();
     if (in_array($post->ID, $do_not_duplicate)) continue;
     ?>
    <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2>
    <?php endwhile; ?>
    <?php else: ?>
    <?php endif; ?>

    <?php get_footer(); ?>

    [mod note – please do not bump, it is not permitted on these forums]

  • The topic ‘Trouble with multiple loops and do_not_duplicate’ is closed to new replies.