4

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?

2
  • 3
    Are you using print or echo in your shortcode handler? Read this.
    – fuxia
    Commented Dec 10, 2012 at 9:57
  • Yes, the problem was in echo's. Thank you for help.
    – drake2300
    Commented Dec 10, 2012 at 10:12

1 Answer 1

14

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.

1
  • 1
    Thanks a lot, return works exactly as I expected.
    – drake2300
    Commented Dec 10, 2012 at 10:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.