Php Wordpress使用echo vs return in shortcode函数

Php Wordpress使用echo vs return in shortcode函数,php,wordpress,shortcode,Php,Wordpress,Shortcode,我注意到echo和return都可以很好地显示wordpress中的快捷码函数中的内容 function foobar_shortcode($atts) { echo "Foo Bar"; //this works fine } function foobar_shortcode($atts) { return "Foo Bar"; //so does this } 使用这两者之间有什么区别吗?如果是,wordpress的推荐方法是什么

我注意到
echo
return
都可以很好地显示wordpress中的快捷码函数中的内容

function foobar_shortcode($atts) {
    echo "Foo Bar"; //this works fine
}

function foobar_shortcode($atts) {
    return "Foo Bar"; //so does this
}

使用这两者之间有什么区别吗?如果是,wordpress的推荐方法是什么?在这种情况下,我通常使用echo,这样可以吗?

这并不是说echo和return是一回事。。只是,一旦echo在您的第一个函数中完成,就没有什么可做的了。。。所以它回来了


在第二个fx中,您显式退出函数并将值返回调用函数。

不同之处在于
echo
将文本直接发送到页面,而不需要函数结束<代码>返回结束函数并将文本发送回函数调用

对于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"

Echo可能适用于您的特定情况,但您绝对不应该使用它。短代码并不意味着输出任何内容,它们应该只返回内容

这里有一个来自短代码法典的注释:

请注意,由短代码调用的函数永远不会产生 任何类型的输出。Shortcode函数应返回 用于替换短代码。直接生产产品 将导致意外的结果

输出缓冲 有时,您会遇到输出变得难以避免或难以避免的情况。例如,您可能需要调用一个函数来在您的快捷码回调中生成一些标记。如果该函数直接输出而不是返回值,则可以使用称为输出缓冲的技术来处理它

输出缓冲将允许您捕获代码生成的任何输出,并将其复制到字符串中

ob\u Start()
启动一个缓冲区,并确保抓取内容并在完成后将其删除,
ob\u get\u clean()
。两个函数之间出现的任何输出都将写入内部缓冲区

例如:

function foobar_shortcode( $atts ) {
    ob_start();

    // any output after ob_start() will be stored in an internal buffer...
    example_function_that_generates_output();

    // example from original question - use of echo
    echo 'Foo Bar';

    // we can even close / reopen our PHP tags to directly insert HTML.
    ?>
        <p>Hello World</p>
    <?php

    // return the buffer contents and delete
    return ob_get_clean();
}
add_shortcode( 'foobar', 'foobar_shortcode' );
函数foobar\u短代码($atts){
ob_start();
//ob_start()之后的任何输出都将存储在内部缓冲区中。。。
示例_函数_生成_输出();
//原始问题示例-echo的使用
回声“foobar”;
//我们甚至可以关闭/重新打开PHP标记以直接插入HTML。
?>
你好,世界

我将使用:

function foobar_shortcode($atts) {
    return "Foo Bar"; //so does this
}
当你在做以下事情时会更容易:

$output = '<div class="container">' . do_shortcode('foobar') . '</div>';
echo $ouput;
$output=''.do_短码('foobar');
回声输出;
稍后..

如果在短代码中使用“echo”,则信息将显示在处理短代码的任何位置,而不一定是您实际添加短代码的位置。如果使用“return”,则信息将准确返回您在页面中添加短代码的位置

例如,如果您有一个图像,然后是短代码,然后是文本:
回声:将在图像上方输出

Return:将在图像之后和文本之前输出(您实际添加了快捷码)

如果您要输出大量内容,则应使用:

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();
}
add_shortcode('test','test_func');
函数测试函数($args){
ob_start();
?> 

一个会立即输出,另一个会将文本返回给调用函数,由调用函数处理输出。它们不一样,功能也不相同。谢谢!这就是我想知道的。该示例很好地说明了这一点。谢谢!这正是我需要的。输出缓冲(ob_start)在PHP中,这是我所不知道的。这里可以找到一些有用的信息来帮助解释这个答案:好吧,它是有效的!现在我可以将我的短代码的内容准确地输出到我期望的地方。