Two loops, exclude post from first loop in second loop

I have a wordpress page which has two loops like so…

<?php 
global $post;
$args = array(
    'showposts'        => 1,
    'category_name'    => 'videos',
    'meta_key'         => 'feature-image',
);

$myposts = get_posts($args);  
foreach( $myposts as $post ) :  setup_postdata($post);
$exclude_featured = $post->ID;
?>
<span class="featured">
<?php the_title(); ?>
</span>
<?php endforeach; ?>

<?php while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>

Now I need to use $exclude_featured in my second loop some how to exclude that post from that loop. I’ve tried a few implementations but none of them have worked. I have tried adding the following above the while statement for the second loop…

Read More
global $query_string;
query_posts( $query_string . '&exclude='.$exclude_featured );

and this…

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'exclude' => $exclude_featured ) );
query_posts( $args );

.. and have had no luck. I’ve noticed that by using either of these two snippets they also render my pre_get_posts function which sets the number of posts to display useless.

Any help would be appreciated

EDIT:

I’ve tried adding the following lines before the while statement on the second loop..

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post__not_in' => $exclude_featured ) );
query_posts( $args );

However I still have not had any success, it brings up the following error:

Warning: array_map() [function.array-map]: Argument #2 should be an
array in
/home/myuser/public_html/mysitedirectory/wp-includes/query.php on line
2162

Warning: implode() [function.implode]: Invalid arguments passed in
/home/myuser/public_html/mysitedirectory/wp-includes/query.php on line
2162

Related posts

Leave a Reply

1 comment

  1. You could substitute your last three lines with these:

    <?php
    while ( have_posts() ) : the_post();
    if ( $exclude_featured == get_the_ID() )
        continue;
    
    the_title();
    endwhile;
    ?>
    

    continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

    This will, however, result in that you’re having one less post to display. If you’d like to keep your post count exactly the same, you would need to exclude the post in the query. The query in the question is pretty close to being correct, but post__not_in has to be an array, and not an integer. All you need to do is wrap your $exclude_featured in an array, and your query should work.

    Your query should look like this:

    global $wp_query;
    $args = array_merge(
        $wp_query->query_vars,
        array(
            'post__not_in' => array(
                $exclude_featured
            )
        )
    );
    query_posts( $args );