Support » Fixing WordPress » If/else have_posts — Else not displaying.

  • Scenario:
    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.

    My Code

    <?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*/?>
    $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>
                    <?php endwhile;
              else:	echo 'No Titles Found';

    Looking at the codex the form of the ‘if else is given as:

    if ( have_posts() ) :
    	while ( have_posts() ) : the_post();
    		// Your loop code
    else :
    	echo wpautop( 'Sorry, no posts were found' );

    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.


Viewing 2 replies - 1 through 2 (of 2 total)
  • Need help with that too… 🙁

    The code below works for me.
    Hope it helps.

    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    // Your loop code
    <?php endwhile; ?>
    <?php else : ?>
    <p>sorry no results</p>
    <?php endif; ?>

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘If/else have_posts — Else not displaying.’ is closed to new replies.