1

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'); ?>
                <h2><a 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();?>
            <h2><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
        <?php endwhile;?>
    <?php endif;?>
</div>
0

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;?>
0

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.

  • this code worked. but all page in archive showing 10 last posts in category! How can I fix this? – ali Jan 25 '17 at 20:09
  • posts_per_page should limit that to 2. If it doesn't, there may be interference from other code in your theme or a plugin. Or you may also be looping through the normal $post query. – cjbj Jan 25 '17 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.