WordPress.org

Forums

[resolved] Echo inside a while loop (4 posts)

  1. brian914
    Member
    Posted 3 years ago #

    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!

  2. alchymyth
    Forum Moderator
    Posted 3 years ago #

    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>';
  3. Chip Bennett
    Theme Review Admin
    Posted 3 years ago #

    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.

  4. brian914
    Member
    Posted 3 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic