If/else have_posts — Else not displaying.
Page displays a list of titles for a custom post type (video) with a selected “category” (in the taxonomy its called the subject). For example videos with the subject of “creative”
If there are titles present that match the the criteria then the list is displayed correctly but if there are no titles then the message “No Titles Found” fails to appear on the page. In other words the echo statement is failing.
<?php $subject = $_GET['subject']; if ($subject=="") $subject = 'creativity';?><?php /*If there is no value returned then the loop defaults to searching for items beginning with 'Creativity' since its the first term.*/ ?> <h2>Video Titles For <span class="colorBlack"><?php echo $subject ?></span></h2> <?php /*This needs to be outside of the loop*/?> <?php $loop = new WP_Query( array( 'post_type' => 'video', 'subject' => $subject, 'posts_per_page' => 10 ) ); ?> <?php if (have_posts() ):?> <?php while ( $loop->have_posts() ) : $loop->the_post();?> <div class="glossarybody"> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2> </div> <?php endwhile; else: echo 'No Titles Found'; endif; ?>
Looking at the codex the form of the ‘if else is given as:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // Your loop code endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?>
So I seem to have the correct syntax and since the ‘if’ section functions correctly I assume it has correct syntax.
I’d appreciate any pointers as to where I’m going wrong.
- The topic ‘If/else have_posts — Else not displaying.’ is closed to new replies.