Shortcode output appears before post body [duplicate]
IT Nursery
May 5, 2022
0
Possible Duplicate:
short code output too early
How can I insert my plugin code via shortcode inside post body in exact position?
The problem is that wp engine inserts the plugin code BEFORE post body all the time. Can it be fixed?
For example: I have some [shortcode option="value"], that generates some text with image inside div container. When I put it inside the post AFTER the text, wp outputs this code:
<div> here is my plugin code </div> <p> here is the text of the post </p>
… and so it gets in the top of the post.
Where is my fault?
1 Answer 1
I have had this problem before: shortcodes shouldn’t display any content (using print or echo), instead return the content to be outputted.
If it’s too much trouble converting all of your output statements, or you need to use a function that will always display the output, you can use output buffering. A buffer will ‘catch’ any echo‘d or print‘d content and allow you to write it to a variable.
function my_awesome_shortcode( $atts, $content = null ) {
// begin output buffering
ob_start();
// output some text
echo 'foo' . "bar\n";
$greeting = 'Hello';
printf( '%s, %s!', $greeting, 'World' );
// end output buffering, grab the buffer contents, and empty the buffer
return ob_get_clean();
}
add_shortcode( 'awesome', 'my_awesome_shortcode' );
Learn more about Output Buffering Control and the different Output Control Functions that you can use.