我刚刚发现echo
和return
都适用于显示短代码功能的内容。
function foobar_shortcode($atts) {
echo "Foo Bar"; //this works fine
}
function foobar_shortcode($atts) {
return "Foo Bar"; //so does this
}
我只是想知道,使用其中任何一个之间有什么区别吗?如果是这样的推荐是什么?在这种情况下我通常使用echo;好吗?
答案 0 :(得分:18)
Echo可能适用于您的具体情况,但您绝对不应该使用它。短代码并不意味着输出任何东西,它们只应返回内容。
以下是关于短代码的代码注释:
请注意,短代码调用的函数永远不会产生 任何形式的输出。短代码函数应该返回文本 用于替换短代码。直接生成输出 会导致意想不到的结果。
http://codex.wordpress.org/Function_Reference/add_shortcode#Notes
答案 1 :(得分:12)
如果要输出大量内容,则应使用:
add_shortcode('test', 'test_func');
function test_func( $args ) {
ob_start();
?> <your contents/html/(maybe in separate file to include) code etc> <?php
return ob_get_clean();
}
答案 2 :(得分:5)
如果在短代码中使用“echo”,则信息将显示在处理短代码的任何位置,这不一定是您实际添加短代码的位置。如果您使用“return”,则信息将准确返回您在页面中添加短代码的位置。
例如,如果您有图像,则为短代码,然后是文字:
Echo:将在图像上方输出
返回:将在图像之后和文本之前(实际添加短代码的地方)输出
答案 3 :(得分:3)
不同之处在于echo
将文本直接发送到页面而不需要结束功能。 return
结束函数并将文本发送回函数调用。
对于echo:
function foobar_shortcode($atts) {
echo "Foo"; // "Foo" is echoed to the page
echo "Bar"; // "Bar" is echoed to the page
}
$var = foobar_shortcode() // $var has a value of NULL
返回:
function foobar_shortcode($atts) {
return "Foo"; // "Foo" is returned, terminating the function
echo "Bar"; // This line is never reached
}
$var = foobar_shortcode() // $var has a value of "Foo"
答案 4 :(得分:1)
它不是回声和回归是一回事......只是一旦回声在你的第一个函数中完成,就没有什么可做的......所以它会返回..
在第二个fx中,您将显式退出该函数并将该值返回给调用函数。
答案 5 :(得分:0)
我会用:
function foobar_shortcode($atts) {
return "Foo Bar"; //so does this
}
当您执行以下操作时更容易:
$output = '<div class="container">' . do_shortcode('foobar') . '</div>';
echo $ouput;
稍后......