Question

I want to use the values returned from two function calls in my echo'ed html string.

<li><a href="the_permalink()">the_title()</a></li>

The following works fine:

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

... but how do I get them all in one single statement?

Was it helpful?

Solution

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

OTHER TIPS

The reason you are having problems is because the_permalink() and the_title() do not return, they echo. Instead use get_permalink() and $post->post_title. Remember get_permalink() requires the post id ($post->ID) as a parameter. I know this is irritating and counter-intuitive, but it's how Wordpress works (see subjectivity in comments to this answer.)

This explains why the second example works in your initial question. If you call function that prints from within a string, the echo will output before the end of the string.

So this:

echo ' this should be before the link: '.the_permalink().' But it is not.';

will not work as expected. Instead, it will output this:

http://example.com this should be before the link: But it is not.

In PHP you can use both single and double quotes. When I am building strings with HTML I generally begin the string with a single quote, that way, I can use HTML-compatible double quotes within the string without escaping.

So to round it up, it would look something like:

echo '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';

Or as you originally requested, to simply escape them, put a backslash before the quote. Like so (the single quotes have been removed)

echo "<li><a href=\"".get_permalink($post->ID)."\">".$post->post_title."</a></li>";

This is of course assuming you are calling this from within the loop, otherwise a bit more than this would be required to get the desired output.

printf( '<li><a href="%s">%s</a></li>', the_permalink(), the_title() );

Using concatenation (line breaks not required):

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

Use <?php the_title_attribute() ?>. It displays or returns the title of the current post. It somewhat duplicates the functionality of the_title(), but provides a 'clean' version of the title by stripping HTML tags and converting certain characters (including quotes) to their character entity equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top