I would like to show all posts but only exclude the NEWEST post from the 'Featured' category, other posts from this cat should display. Any idea what I should add to the loop to achieve this? I want all other posts from other cats to be displayed aswell!
2 Answers
A while back i posted a simple function that gets latest post in a certain category:
function get_lastest_post_of_category($cat){
$args = array( 'posts_per_page' => 1, 'order'=> 'DESC', 'orderby' => 'date', 'category__in' => (array)$cat);
$post_is = get_posts( $args );
return $post_is[0]->ID;
}
So once you have that function you can use use WP_Query or query_posts and using the post__not_in
parameter you can exclude that post, so something like:
query_posts(array(`post__not_in` => array(get_lastest_post_of_category($CAT_ID))));
just change $CAT_ID to the actual category id
Since by default the loop will retrieve the posts in descending order by date, you can do something like the following:
Outside the loop:
$featured_flag = false;
Inside the loop:
if(in_category('Featured')) {
if($featured_flag) {
the_content();
}
else {
$featured_flag = true;
}
}
else {
the_content();
}
The first time a post from the Featured category is encountered (i.e. the most recent) it will be ignored and the $featured_flag
will be set to true
. Subsequent times through the loop the_content()
will be displayed.
Edit: To account for pagination you could change $featured_flag
to a $_SESSION
variable. That way the true/false value will persist across multiple pages, and once it's been set to true
posts will continue to display properly. Thanks for pointing out the error of my ways Bainternet :)
-
that's nice, and would work unless you have pagination, which will get messed up. Commented May 1, 2011 at 19:54
-
Edited to account for pagination (theoretically). Thanks for pointing that out. Commented May 1, 2011 at 20:04
-
That will make sure the post is only seen once, and if you simply reload you won't see that post again untill a new session is started, and it will still mess up the pagination, think about it, you have a posts_per_page which will get a number of posts as defined and the loop will show one less. Commented May 1, 2011 at 20:27
-
Ya, you're right. I didn't really think it through fully. It's late and I need to sleep :) Commented May 1, 2011 at 20:32