Wordpress using echo vs return in shortcode function

后端 未结 6 2198
我在风中等你
我在风中等你 2021-01-01 22:07

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

function foobar_short         


        
6条回答
  •  忘掉有多难
    2021-01-01 22:25

    The difference is that echo sends the text directly to the page without the function needing to end. return both ends the function and sends the text back to the function call.

    For 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
    

    For return:

    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"
    

提交回复
热议问题