WordPress.org

Ready to get started?Download WordPress

Forums

If/else have_posts -- Else not displaying. (3 posts)

  1. dorich
    Member
    Posted 3 years ago #

    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"

    Problem
    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*/?>
    
    <?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.

    Thanks.

  2. ilankibrit
    Member
    Posted 2 years ago #

    Need help with that too... :-(

  3. carlafranca
    Member
    Posted 2 years ago #

    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; ?>

Topic Closed

This topic has been closed to new replies.

About this Topic