Wordpress在简码函数中使用echo vs return [英] Wordpress using echo vs return in shortcode function

查看:32
本文介绍了Wordpress在简码函数中使用echo vs return的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 echoreturn 都可以很好地显示 wordpress 中来自简码函数的内容.

I noticed both echo and return works fine for displaying content from a shortcode function in wordpress.

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

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

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

Is there any difference between using either of these? If yes, what's the recommended approach for wordpress? I normally use echo in this case - is this okay?

推荐答案

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

Echo may work in your specific case but you definitely shouldn't use it. Shortcodes aren't meant to output anything, they should only return content.

以下是关于短代码的代码注释:

Here's a note from the codex on shortcodes:

请注意,短代码调用的函数不应产生任何类型的输出.短代码函数应该返回文本用于替换短代码.直接输出会导致意想不到的结果.

Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results.

http://codex.wordpress.org/Function_Reference/add_shortcode#Notes

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

Sometimes you're faced with a situation where output becomes difficult or cumbersome to avoid. You may for example need to call a function to generate some markup within your shortcode callback. If that function were to output directly rather than return a value, you can use a technique known as output buffering to handle it.

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

Output buffering will allow you to capture any output generated by your code and copy it to a string.

使用 ob_start() 启动缓冲区,并确保在完成后获取内容并删除它,ob_get_clean().两个函数之间出现的任何输出都将写入内部缓冲区.

Start a buffer with ob_start() and make sure to grab the contents and delete it when you're finished, ob_get_clean(). Any output appearing between the two functions will be written to the internal buffer.

示例:

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

这篇关于Wordpress在简码函数中使用echo vs return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆