3zz*_*zzy 5 php string-concatenation
我想在echo'ed html字符串中使用从两个函数调用返回的值.
<li><a href="the_permalink()">the_title()</a></li>
以下工作正常:
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
Run Code Online (Sandbox Code Playgroud)
......但我如何在一个声明中得到它们?
San*_*ich 10
您遇到问题的原因是因为the_permalink()和the_title()没有返回,它们会回显.而是使用get_permalink()和$ post-> post_title.请记住,get_permalink()需要post id($ post-> ID)作为参数.我知道这很烦人且反直觉,但它是Wordpress的工作原理(请参阅评论中的主观性来回答这个问题.)
这解释了为什么第二个例子适用于您的初始问题.如果调用从字符串中打印的函数,则echo将在字符串结尾之前输出.
所以这:
echo ' this should be before the link: '.the_permalink().' But it is not.';
Run Code Online (Sandbox Code Playgroud)
不会按预期工作.相反,它会输出:
http://example.com this should be before the link: But it is not.
Run Code Online (Sandbox Code Playgroud)
在PHP中,您可以使用单引号和双引号.当我使用HTML构建字符串时,我通常用单引号开始字符串,这样,我可以在字符串中使用HTML兼容的双引号而不转义.
所以要把它整理一下,它看起来像是这样的:
echo '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
Run Code Online (Sandbox Code Playgroud)
或者按照您最初的要求,简单地逃避它们,在引用之前加上反斜杠.像这样(单引号已被删除)
echo "<li><a href=\"".get_permalink($post->ID)."\">".$post->post_title."</a></li>";
Run Code Online (Sandbox Code Playgroud)
这当然是假设你是在循环内调用它,否则需要比这更多一点来获得所需的输出.
echo '<li><a href="', the_permalink(), '">', the_title(), '</a></li>';
Run Code Online (Sandbox Code Playgroud)