Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Running Extra Loops
- It's important to be aware that while you can use WP_Query to run more than one loop, you have to reset the post data and start a second instance of WP_Query to do this. This is because each of your loops will be outputting data based on different arguments.
- This example displays the excerpt and featured image for the first post and then just the title of each subsequent post:
- <?php
- // First query arguments.
- $args1 = array(
- 'post_type' => 'post',
- 'posts_per_page' => '1'
- );
- // First custom query.
- $query1 = new WP_Query( $args1 );
- // Check that we have query results.
- if ( $query1->have_posts() ) {
- // Start looping over the query results.
- while ( $query1->have_posts() ) {
- $query1->the_post();
- ?>
- <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
- <?php post_thumbnail( 'thumbnail' );?>
- </a>
- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
- <?php the_title(); ?>
- </a>
- <?php the_excerpt(); ?>
- </article>
- <?php
- }
- }
- // Restore original post data.
- wp_reset_postdata();
- // Second query arguments.
- $args2 = array(
- 'offset' => '1',
- 'post_type' => 'post'
- );
- // Second custom query.
- $query2 = new WP_Query( $args2 );
- // Check that we have query results.
- if ( $query2->have_posts() ) {
- echo '<ul class="more-posts">';
- // Start looping over the query results.
- while ( $query2->have_posts() ) {
- $query2->the_post();
- ?>
- <li <?php post_class(); ?>>
- <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
- <?php the_title(); ?>
- </a>
- </li>
- <?php
- }
- echo '</ul>';
- }
- // Restore original post data.
- wp_reset_postdata();
- ?>
- I've used two key arguments here:
- 'posts_per_page' => '1', used with the first query, outputs just the most recent post.
- 'offset' = '1', used with the second query, skips the first post, ensuring it's not repeated in the list below.
- As you can see from the code above, the loop is slightly different for each query. The first one outputs the featured image, title and excerpt, while the second checks if the query has posts and if so, opens a ul element and encloses each post title in a li element and a link to its page.
- You'll also notice that I used wp_reset_postdata() after both loops. If I hadn't done this, the second loop would still output data from the first.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement