Wordpress using echo vs return in shortcode function
If you are outputting a lot of contents, then you should use:
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 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
Output Buffering
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.
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.
Example:
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