Two loops on archive page

I have 2 loops on the archive page. I want the first loop to display the 2 last posts of the category and the second loop offset 2 last post!

div class="top-posts"
    ?php
    if (have_posts()) :
        while(have_posts()) : the_post();?
            div class="content"
                ?php the_post_thumbnail('archive'); ?
                h2a href="?php the_permalink(); ?"?php the_title(); ?/a/h2
            /div
        ?php endwhile;?
    ?php endif;?
/div

div class="primary-posts"
    ?php
    if (have_posts()) :
        while(have_posts()) : the_post();?
            h2a href="?php the_permalink(); ?" ?php the_title(); ?/a/h2
        ?php endwhile;?
    ?php endif;?
/div

Topic loop wp-query theme-development archives Wordpress

Category Web


Once you've exhausted the loop, you need to reset it by using rewind_posts() before you go into your second loop:

<?php
rewind_posts();
if (have_posts()) :
    while(have_posts()) : the_post();?>
        <h2><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
    <?php endwhile;?>
<?php endif;?>

From your question it is not clear which posts you want to select precisely. In any case, you clearly want to display different posts than are normally presented on the archive page. This means you will need to make a different selection in your template, using wp_query. The trick is to select the right arguments.

First, for use later on, we need to retrieve the ID of the archive from the main archive loop. This will return the category ID on a category archive page (or the tag ID on a tage archive page, and so on)

$cat_id = $wp_query->get_queried_object_id()

Now, we can build the right arguments to select the two first entries in this category, and show them in a separate loop, like this:

$args = array (
  'cat'            => $cat_id,
  'posts_per_page' => 2,
  ) 

$the_query = new WP_Query ($args);
if ($the_query->have_posts()) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        // display stuff
        }
    wp_reset_postdata(); // restore the original archive loop
    }

If you want to select all posts, regardless of category, on this category archive page, you would repeat the above, but leave the 'cat' line in $args out.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.