WordPress.org

Support

Support » Themes and Templates » [Resolved] Echo inside a while loop

[Resolved] Echo inside a while loop

  • I am trying to do the following to get links to my pages. I am using this:

    if ( have_posts() ) : while ( have_posts() ) : the_post();
    	echo '<li><a href="#">' . the_title() . '</a></li>';
    endwhile; else:
    	//echo 'Sorry, no pages matched your criteria.';
    endif;

    and this output this in my html:

    Client Name<li><a href="#"></a></li>

    yet, I want it to output this, like a proper link/li would look like:

    <li><a href="#">Client Name</a></li>

    Why is that happening and how can I fix this?

    Thanks a lot for any help with this!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Michael

    @alchymyth

    http://codex.wordpress.org/Function_Reference/the_title

    two possibilities:

    either:

    echo '<li><a href="#">'; the_title(); echo '</a></li>';

    or:

    echo '<li><a href="#">' . the_title('','',false) . '</a></li>';

    Chip Bennett

    @chipbennett

    Theme Review Admin

    The the_title() function echoes by default. Re-echoing it may cause unintended output.

    I would suggest using the following, rather than echoing lines of HTML:

    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    	<li><a href="#"><?php the_title(); ?></a></li>
    <?php endwhile; else:
    	//echo 'Sorry, no pages matched your criteria.';
    endif;

    I assume you’re adding the containing list tags (UL or OL) outside of the Loop? Note that if you’re doing so, you’ll want to output your else content (e.g. Sorry, no pages matched your criteria.) inside of list-item tags (LI), too, in order to maintain correct markup.

    Thank you very much for the response!!! This answered my question.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] Echo inside a while loop’ is closed to new replies.