使用Echo vs返回的WordPress在短代码函数中返回



我注意到 echoreturn都可以在WordPress中显示快捷代码函数的内容。

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

使用其中任何一个之间有任何区别吗?如果是,WordPress推荐的方法是什么?在这种情况下,我通常使用echo-可以吗?

ECHO在您的特定情况下可以工作,但您绝对不应该使用它。短号并不意味着输出任何内容,它们只能返回内容。

以下是短代码上的注释:

请注意,短代码调用的功能永远不应产生任何形式的输出。短码函数应返回文本用于替换短代码。直接产生输出将导致意外结果。

http://codex.wordpress.org/function_reference/add_shortcode#notes

输出缓冲

有时,您面临着产出变得困难或繁琐避免的情况。例如,您可能需要调用功能以在短代码回调中生成一些标记。如果该功能是直接输出而不是返回值,则可以使用称为输出缓冲的技术来处理它。

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

使用ob_start()启动缓冲区,并确保抓住内容并在完成后删除它,ob_get_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' );

https://www.php.net/manual/en/function.ob-start.php

如果要输出很多内容,则应使用:

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();
}

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

例如回声:将在图像上方输出
返回:将在图像之后和文本之前输出(您实际添加了短代码)

我会使用:

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

当您做以下操作时,这很容易:

$output = '<div class="container">' . do_shortcode('foobar') . '</div>';
echo $ouput;

后来..

区别在于, echo无需结束功能即可将文本直接发送到页面。return两者都结束功能,并将文本发送回功能调用。

回声:

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"

它不是回声和返回是同一回事。.只是一旦回声在您的第一个功能中完成,就无关紧要...所以它返回.. p>在第二个FX中,您明确退出了该功能,并将值返回到调用函数。

最新更新