WordPress ShortCode API – How to make a function echo and not break

According to my previous understanding and WordPress’s documentation:

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

So, we’re limtied, shortcode functions must return, not echo. So:

https://gist.github.com/davidsword/394108430a76c36aa9cefb6c809dc187

Has been my understanding for years. Unless…

https://gist.github.com/davidsword/1a590c2a11bb55531ddfc98eb83afee3

Yeah. Yeah. That’s right! You can use output buffering to collect your echo’ed HTML from printing, and return it instead.

This is good to use when a shortcode has dozens of lines some multi-language script. For example I’m working on a custom Google Map with Javascript, it’s 200 lines, called to via [map] and has lots of PHP, HTML, some CSS, and WordPress conditional statements weaved into it. It’s a nightmare putting that much Javascript and multi-language markup into a PHP string, escaping quotes alone is a pile of trouble. What’s worse is the syntax highlighting from the IDE is lost, so any bug fixes or changes, you loose a great assistant. I know there’s other solutions, I could build a class, or I could do a file_get_contents() and reduce my PHP to being at the top of the script, or similar, but when the scripts not too long, it’s just so nice to have raw HTML inside the function, instead of dealing with everything else.


Update: Another great use for this is if you want to include() a local file’s echo‘ed results into a variable. If you use get_file_contents() you’ll receive the unexecuted code, storing executed code in an object allows you to return it into a variable. For the following example /file.php is just a simple file with echo "Rock the boat";

https://gist.github.com/davidsword/29aa612b73266c72b79e41bddbe01174

With the above, $files_output will be Rock the boat. Neat eh!