[Solved] The Double Loop Nightmare
-
Hi.
I have my own theme. I was trying to make two loops, first for the sticky posts, and the second for the normal posts.This is the code I used for my theme:
<?php // Create array of all the sticky_posts $stickies = get_option( 'sticky_posts' ); // Count how many there are, if any $count = count( $stickies ); // Create a set of arguments to pass $args = array( 'post__in' => $stickies, // 'posts_per_page' => 3, commented out so it displays all 'post_type' => 'post', 'nopaging' => true ); $featured = new WP_Query( $args ); // If there is one or more sticky post we create our new slider if ( $count > 0 ) : ?> <ul id="sticky"> <?php while( $featured->have_posts() ) : $featured->the_post(); ?> <!-- loop code --> <?php endwhile; wp_reset_query(); ?> </ul> <?php endif; // end the featured posts ?> <ul id="posts"> <?php $count = 1; $col_count = 3; $num_of_posts = $wp_query->post_count; $post_per_column = ceil($num_of_posts / $col_count); ?> <div id="col1"> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <!--loop code--> <?php if($count == $post_per_column) { echo '</div><div id="col2">'; } if($count == 2*$post_per_column) { echo '</div><div id="col3">'; } $count++; endwhile; ?> </div><!--end #col --> </ul> <?php else: ?> <!--404--> <?php endif; ?>It worked, but late I noticed that the sticky posts were displayed in all the pages of my blog.Another important problem is that the sticky posts are also displayed in the second loop. To fix the second problem
But It doesnt worked.I tried the solution of esmi and keesiemejier answer in this topic: How can I exclude sticky post-from-custom-loop?. But it dindn’t worked too. Also I tried with
'post__not_in' => get_option("sticky_posts"),But the same problem.
With all those pieces of codes the problem was the same: the loop didn’t showed any post. In the home page I couldnt saw anything.
Then I tried<?php $the_query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>And I looked like the problem was fixed, but the pagination didn’t worked and the same posts in first page was always showed in all pages.
Finally I tried with this code in the second loop:
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $sticky=get_option('sticky_posts'); $args = array( 'post__not_in' => $sticky, 'paged' => $paged ); $posts = new WP_Query( $args ); ?> <?php if (have_posts()): while ($posts->have_posts()) : $posts->the_post(); ?>and then all worked.
Any idea about why didn’t made the other ones?
The topic ‘[Solved] The Double Loop Nightmare’ is closed to new replies.