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?
An easy workaround is to use Output control functions:
Follow this link http://codex.wordpress.org/Shortcode_API#Overview
So all shortcode function must be return, you can change your function “wanted” to this:
Using Ruslan Bes‘ answer, the code looks like this:
The WordPress standard way would be to provide two functions. One,
get_wanted()
would return the wanted string; the other,wanted()
, is just:So you can do either, but only have the bulk of the code in one place. This is a common pattern in WordPress, e.g.
the_title()
versusget_the_title()
.As @Ruslan mentions, the most standard way without rewriting your existing function to build a string would be to use output control.