我发现'echo'和'return'都可以在shortcode函数中显示。
function display_shortcode_content($atts) {
echo "COMES";
}
function display_shortcode_content($atts) {
return "COMES";
}
我的疑问是函数中echo和retutn之间的区别是什么?
echo用于获取函数的最终结果以获得输出。
return用于返回函数的值。
<?php
function bar() { return 'bar'; }
$baz = bar();
echo $baz;
?>
最佳实践是使用return。例如,如果你有这样的东西:
<div>
<h1>Random Title</h1>
[your_shortcode]
</div>
在你的shortcode函数中,如果你回显一些标记,标记将出现在div和h1之前,就像你使用return一样,它将出现在shortcode的位置,它应该在那里。