query_posts exclude a meta key

I’ve never had any luck getting the meta compare to work either–but I came up with a workaround for this exact situation (having “featured” items at the top of the page).

First, you probably shouldn’t be using query_posts for both queries. You should use a custom query for at least the first one. Then, while you’re running that loop, keep the ids of any “featured” posts in a variable. When you run your second loop, you can use the “post__not_in” arg to exclude the featured ones. Like so:

// Set up a custom query
$featured_query = new WP_query();

// Your query args
    $featured_args=array(
        'post_type'=>'post',
        'meta_key'=>'featured_product',
        'meta_value'=>'1'
    );

// Run it
    $featured_query->query($featured_args);

    if ($featured_query->have_posts()) {

    while ($featured_query->have_posts()) {

            $featured_query->the_post();

        // Remember the featued ID
        $featured_post_id = get_the_ID(); 

        // Render your featured post here

    }

}

// Set up the args for your main query
$args = array(
        'post_type' => 'post',
        'post__not_in' => array($featured_post_id) // Don't show the featured post
    );

// Now run your main query and so on...

Leave a Comment