how to exclude “featured” posts from the main loop?

In a category.php template, I built a function that lists “featured” posts before the main loop. The featured posts are selected using a custom field and get_posts():

function list_featured_articles(){
 $featured_posts = get_posts('meta_key=featured_article&meta_value=on&numberposts=10&order=DESC&orderby=post_date');
}

My category.php template:

Read More
echo list_featured_articles();
get_template_part( 'loop', 'category' );

It works fine, except that the featured articles are listed also in the category list of articles.
I would like, from my function, get the featured posts’ ID and remove them from the main loop.
Is there a proper way to do it? I figure i could use a GLOBAL variable storing an array of excluded ids, but i’d like to avoid using Globals for that.

Related posts

Leave a Reply

1 comment

  1. This would be an appropriate use of query_posts(), with a post custom meta query.

    Since you’re querying by meta_key=featured_article&meta_value=on, you would then exclude on the same parameters.

    <?php
    // Setup the custom meta-query args
    $exclude_featured_args = array(
        'meta_query' => array(
            array(
                'key' => 'featured_article',
                'value' => 'on',
                'compare' => '!='
            )
        )
     );
    // globalize $wp_query
    global $wp_query;
    // Merge custom query with $wp_query
    $merged_args = array_merge( $wp_query->query, $exclude_featured_args );
    // Query posts using the modified arguments
    query_posts( $merged_args );
    ?>
    

    That should exclude featured posts from the main loop.

    Note: you’ll only want to do this in the same context in which you display the featured posts loop.

    EDIT

    From your comment:

    my function is set up so that if there are no “featured” post, it automatically takes the most recent ones and display them as “featured”

    Again, you can take whatever method you use to include posts in your featured loop, and then use the same arguments to exclude the same posts from the primary Loop.

    Without knowing what your method is, I can’t give a precise answer for how to incorporate it into your excluded-posts argument array.