Second Loop in Sidebar of Twenty Ten Child Theme
-
I’m working on a child theme of Twenty Ten where I want to run a second loop in the sidebar for single posts and categories that will list recent posts minus the post(s) already shown on the page.
I am storing the ID’s of the original posts in an array named $ids, then excluding those ID’s in the second loop.
Here’s the weird part. If I add the second loop after the first in loop.php, it works as intended. But if I add the second loop to sidebar.php, it fails to exclude the original posts. Some testing reveals that the variable $ids loses it’s content going from the loop.php to sidebar.php. Here’s the code, with all of the extra stuff stripped out:
<?php $ids = array(); while (have_posts()) : the_post(); $ids[] = get_the_ID(); ?> <h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <?php endwhile; // End the loop. Whew. ?> <!-- print out the Post ID, category, and what's stored in the variable $ids --> <p>Result of print_r($ids): <?php print_r($ids) ?></p> <hr /> <!-- Second loop ******************************** --> <?php // Create a new instance $second_query = new WP_Query(array('post__not_in' => $ids)); // The Loop while( $second_query->have_posts() ) : $second_query->the_post(); echo '<li>'; the_title(); echo '</li>'; endwhile; wp_reset_query(); ?> <!-- End of Second Loop ****************** -->
So far, this does what I want it to. To get the same result in the sidebar, I’m using:
<!-- print out the Post ID, category, and what's stored in the variable $ids --> <p>Result of print_r($ids): <?php print_r($ids) ?></p> <?php // Create a new instance $third_query = new WP_Query(array('post__not_in' => $ids)); // The Loop while( $third_query->have_posts() ) : $third_query->the_post(); ?> <?php echo '<li>'; the_title(); echo '</li>'; endwhile; wp_reset_query(); ?>
For some reason, it fails. The output of that print_r($ids) command at the end of the loop.php is the array of post-IDs, as it should be. The output of print_r($ids) at the top of sidebar.php is empty, thus the third_query fails to exclude those posts.
Any suggestions?
- The topic ‘Second Loop in Sidebar of Twenty Ten Child Theme’ is closed to new replies.