WordPress ShortCodes – Make a function echo & not error
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
Has been my understanding for years. Unless…
Yeah. Yeah. That’s right! You can use output buffering to collect your echo’ed HTML from printing, and return it instead.
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";
With the above,
$files_output will be
Rock the boat. Neat eh!