Shortcode output appears before post body [duplicate]

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.

Leave a Comment