Reputation: 40
I'm trying to figure out a way to exclude posts that are marked as "featured" from the "recent posts" page.
As you can see below, my recent posts page only shows posts from 2 categories (cat1 and cat2). The problem is, once in awhile, I'll add a post to one of the categories below, and mark it as "featured link" or whatever. So when you view the page, you basically see the featured post in the header(OUT of loop), and within the body (IN the loop). How would I go about removing the featured post that is IN the loop?
<?php
// args query
$args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'order' => 'DESC',
// display only posts in specifics categories (slug)
'category_name' => 'cat1, cat2'
);
// custom query
$recent_posts = new WP_Query($args);
// check that we have results
if($recent_posts->have_posts()) : ?>
<?php
// start loop
while ($recent_posts->have_posts() ) : $recent_posts->the_post();
?>
For anyone wondering, I tried the following, but it didn't work:
$args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'order' => 'DESC',
// display only posts in specifics categories (slug)
'category_name' => 'cat1, cat2',
'meta_query' => array(
array(
'key' => 'featured',
'value' => 'yes',
'compare' => 'NOT LIKE',
),
),
);
When adding the 'meta_query' thing that others suggested, it seems the page stops displaying results all together.
Any idea of how to correctly write this out and maybe offer additional alternative solutions too?
Thanks.
Upvotes: 0
Views: 745
Reputation: 811
Another way is that you can use 'post__not_in' => array (//post ids you want to exclude)
in your wp_query
Upvotes: 0
Reputation: 1794
Tested working good. just replace 'compare' => 'NOT LIKE'
to 'compare' => 'NOT EXISTS'
. Hope this help you.
// args
$args = array(
'numberposts' => 3,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'featured',
'value' => 'yes',
'compare' => 'NOT EXISTS',
),
),
);
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
while( $the_query->have_posts() ) : $the_query->the_post();
echo the_title();
endwhile;
endif;
wp_reset_query();
Upvotes: 0