Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate strings with function calls while using echo?

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?

like image 480
eozzy Avatar asked Feb 11 '10 07:02

eozzy


People also ask

How do you echo a string function?

The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.

How do you combine strings with variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

What function is used to concatenate strings?

Use CONCATENATE, one of the text functions, to join two or more text strings into one string. Important: In Excel 2016, Excel Mobile, and Excel for the web, this function has been replaced with the CONCAT function.


1 Answers

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.

like image 98
ThiepLV Avatar answered Nov 15 '22 04:11

ThiepLV