So I’m adding a alert section to my blog, that only shows the content of posts that are included within the “alert” category and are “sticky”.
This all works as it should. I’m wondering now how I can hide the wrapping div that shows these alerts if none exist.
This is what I have so far…
/* This is the if statement that i'm having trouble with */
<?php if (have_posts() && in_category('alert')) {?>
/* Below here works fine */
<div id="alert">
<div class="wrapper">
<div class="close"><i class="fa fa-times"></i></div>
<div class="ticker">
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
if(is_sticky() && in_category('alert')) {?>
<li>
<strong><?php the_title(); ?> - </strong>
<?php the_content(); ?>
</li>
<?php } ?>
<?php endwhile; else: ?>
<?php endif; ?>
</ul>
</div>
</div>
</div>
<?php } ?>
As I already stated in comments, you should never ever use
query_posts
as it breaks the main query object, and many plugins and custom code relies on this object. If you have to run a custom query, useWP_Query
orget_posts
.Secondly, your query is ineffecient and wasteful. You are currently querying all sticky posts and then skipping posts inside the loop with the use of conditional tags. All of this runs unnecessary db calls which wastes resources.
To correct your issue, we will:
WP_Query
and setno_found_rows
to true to skip paging as we don’t need paginationuse
ignore_sticky_posts
to ignore sticky posts to be moved to the frontuse the
cat
(use category ID) orcategory_name
(uses category slug) parameter to get posts from the specific categoryYou can try something like this: (I’m not going to code the loop, but you need use yours, just remember to remove the conditional checks,
is_sticky()
andin_category()
)EDIT
I have slipped up here. When there are no sticky posts,
get_option( 'sticky_posts' )
will return an empty array. If you pass an empty array topost__in
, it will return all posts. It is a stupid bug in theWP_Query
class. IMHO, an empty array should result in no posts. I have updated the code to gaurd againt this