2

I have 2 loops on a page. The first displaying 2 featured posts:

<?php
$args = array(
    'posts_per_page' => '2',
    'meta_query' => array(
        array(
            'key' => 'featured_post',
            'value' => '1',
            'compare' => 'LIKE'
        )
    )
);
query_posts($args);
?>

The second display all posts:

<?php wp_reset_query(); ?>
                <?php if (have_posts()) : ?>
                    <?php while (have_posts()) : the_post(); ?>

                <div class="meta">DO STUFF</div>

                    <?php endwhile; ?>
                <?php endif; ?>

How can I exclude the first 2 "featured_post" items from the second loop?

3
  • Write the postID of the first two posts to an array and then add a post__not_in argument to the second query: post__not_in => $my_array codex.wordpress.org/Class_Reference/…
    – jdm2112
    Sep 7, 2016 at 13:39
  • That kind of makes sense. How can I write the first two IDs into an array? Thanks
    – Phil
    Sep 7, 2016 at 13:51
  • Do an initial query with a limit of 2 and then add those IDs to your next query.
    – Fencer04
    Sep 7, 2016 at 14:11

1 Answer 1

1

First point is that you should NOT use query_posts() for custom queries. The better approach is to use the WP_Query class. More info in the WP docs and here.

This example will display your 2 featured posts and then exclude them in the second query.

// We will push the ID of your featured posts to this array
$excl_posts[] = '';

// Query arguments from your featured posts query
$feat_args = array(
    'posts_per_page' => '2',
    'meta_query' => array(
        array(
            'key' => 'featured_post',
            'value' => '1',
            'compare' => 'LIKE'
        )
    )
);

// Instantiate new WP_Query instead of using query_posts()
$featured = new WP_Query( $feat_args );

if ( $featured->have_posts() ):
  while ( $featured->have_posts() ):
    $featured->the_post();

    // Do stuff with each posts
    echo get_the_title() . "<br>";

    // Push current postID onto the exclude array
    $excl_posts[] = get_the_ID();
  endwhile;
endif;

wp_reset_postdata();

$excl_feat_args = array(
    'posts_per_page' => '10',
    'post__not_in' => $excl_posts,
    'meta_query' => array(
        array(
            'key' => 'featured_post',
            'value' => '1',
            'compare' => 'LIKE'
        )
    )
);
$excl_featured = new WP_Query( $excl_feat_args );

if ( $excl_featured->have_posts() ):
  while ( $excl_featured->have_posts() ):
    $excl_featured->the_post();
    echo get_the_title() . "<br>";
  endwhile;
endif;

wp_reset_postdata();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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