Search code examples
phpwordpresspluginsshortcode

Wordpress shortcodes in the wrong place


I'm making wordpress plugin and I want to use shortcodes to insert some quite huge code inside post. I got this simple code that simulates my problem

function shortcode_fn( $attributes ) {
    wanted();
    return "unwanted";
}
add_shortcode( 'simplenote', 'shortcode_fn');

function wanted(){
    echo "wanted";
}

and post with this content

start
[simplenote]
end

that gives this result:

wanted
start
unwanted
end

and I want it to insert "wanted" text between start and end. I know easiest solution would be to just return "wanted" in wanted(), but I already have all these functions and they're quite huge. Is there a easy solution without writing everything from scratch?

@edit: maybe is there some way to store all echoes from function in string without printing it?


Solution

  • An easy workaround is to use Output control functions:

    function shortcode_fn( $attributes ) {
        ob_start(); // start a buffer
        wanted(); // everything is echoed into a buffer
        $wanted = ob_get_clean(); // get the buffer contents and clean it
        return $wanted;
    }