Solution to a closed but not well resolved question
-
If you search Google for “wordpress shortcode outputs wrong place” (no quotes), the top link is to this www.ads-software.com Support Forums post. That question is 3 years old, closed, and there is no easily found resolution in that thread, yet Google considers it ”the best article” regarding those key words.
I propose that the my solution below, or another deemed better, be moved to that thread. The number one result of a Google search using those keywords should not point to an unresolved, closed www.ads-software.com Support Forum thread – it should be to a www.ads-software.com Solution.
And maybe include in the original question a “TL;DR, see the solution at the bottom” type of statement for those who don’t want to wade through the many posts in that thread (or give up before reaching the solution).
Edit: Fixed code formatting.
——— Start proposed solution ———
The shortcode callback function shouldn’t be echoing to the screen. Just like a normal WordPress filter callback function, you shouldn’t be sending output to the screen, or include’ing/require’ing PHP files that do so, without buffering. The output should be buffered usingob_start()
then stored in a string for proper handling by the WordPress’s Shortcode APIThe commented code below shows how to properly buffer any output from
echo
statements and/or PHP scripts called withinclude()
,require()
.<?php add_shortcode( 'my_shortcode', 'my_shortcode_callback_function' ); function my_shortcode_callback_function() { // turn on output buffering ob_start(); // echo's and HTML won't be written to the screen yet echo 'Hello, World! I\'m being buffered!'; ?> <div> This text is also being buffered. It won't be output to the screen until the variable $output (below) is returned to the Shortcode API for proper insertion. </div> <?php // same as before, any echo's and HTML resulting from include(), // require(), etc., won't be output to the screen yet include( '/path/to/my/file.php' ); // store the buffered text, HTML, & PHP into a string variable; // any PHP code that has been buffered will be processed and executed // at the place where [my_shortcode] is located in your post/page $output = ob_get_contents(); // turn off output buffering, throwing away what was in the buffer, // which is what we want since we already stored the buffer's contents // in in the variable $output ob_end_clean(); // pass the buffered stuff back to the Shortcode API return $output; }
- The topic ‘Solution to a closed but not well resolved question’ is closed to new replies.