php - WordPress Checking if post exists with category outside loop -


so i'm adding alert section blog, shows content of posts included within "alert" category , "sticky".

this works should. i'm wondering how can hide wrapping div shows these alerts if none exist.

this have far...

        /* if statement i'm having trouble */                 <?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 stated in comments, should never ever use query_posts breaks main query object, , many plugins , custom code relies on object. if have to run custom query, use wp_queryor get_posts.

secondly, query ineffecient , wasteful. querying sticky posts , skipping posts inside loop use of conditional tags. of runs unnecessary db calls wastes resources.

to correct issue, will:

  • wp_query , set no_found_rows true skip paging don't need pagination

  • use ignore_sticky_posts ignore sticky posts moved front

  • use cat (use category id) or category_name (uses category slug) parameter posts specific category

you can try this: (i'm not going code loop, need use yours, remember remove conditional checks, is_sticky() , in_category())

$stickies = get_option( 'sticky_posts' ); if ( $stickies ) {     $args = [         'post__in' => $stickies,         'ignore_sticky_posts' => 1,         'no_found_rows' => true,         'cat' => 1, // change correct id         //'category_name' => 'cat-slug',     ];     $q = new wp_query( $args );     if ( $q->have_posts() ) {         while ( $q->have_posts() ) {         $q->the_post();              // loop          }         wp_reset_postdata();     } } 

edit

i have slipped here. when there no sticky posts, get_option( 'sticky_posts' ) return empty array. if pass empty array post__in, return all posts. stupid bug in wp_query class. imho, empty array should result in no posts. have updated code gaurd againt this


Comments