Wordpress, if there are no loop results, does not display the title

I am using WP_Query to loop through a custom post type in wordpress. My loop looks like this:

<div class="bigRedStrip"> <h2>Available Now!</h2> </div> <ul> <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <li> loop stuff here </li> <?php endwhile; ?> </ul> 

As you can see, before the loop there is a heading that says "Available now!". I want to reformat the loop, so if there are no messages returned, then the div containing the title (bigRedStrip div class) will not be displayed. I tried a number of potential solutions, but the problem I am facing is that all of these "solutions" require placing <div class="bigRedStrip"> inside the loop, which leads to a repetition of the header for each returned message. The idea is for the title to be displayed only once. Any ideas how I can do this?

+4
source share
2 answers

You only need to make out things a little. First of all, run the query:

 <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?> 

Then check if there is something:

 <?php if ($loop->have_posts()) { ?> <div class="bigRedStrip"> <h2>Available Now!</h2> </div> ... 

And if so, just iterate over the messages:

 ... <ul> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <li> loop stuff here </li> <?php endwhile; ?> </ul> <?php } ?> 
+5
source
 <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?> <?php if ($loop->have_posts()){ <div class="bigRedStrip"> <h2>Available Now!</h2> </div> <ul> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <li> loop stuff here </li> <?php endwhile; ?> </ul> <?php } ?> 
0
source

Source: https://habr.com/ru/post/1403231/


All Articles