Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 427
zbyshekh Avatar asked Apr 28 '14 06:04

zbyshekh


People also ask

How do I override a shortcode in WordPress?

We need to use the wp_head action hook to override our shortcode. We have used the remove_shortcode() function to remove the shortcode and add_shortcode() to override it according to needs. Now define your codes in the cpc_services_list_item_shortcode function.

Where are WordPress shortcodes stored?

Using WordPress Shortcodes in Pages and Posts If you're using the Gutenberg editor, you can add the shortcode tag in the standalone Shortcodes block. We can find it in the Widgets section.


1 Answers

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;
}
like image 112
Ruslan Bes Avatar answered Oct 12 '22 15:10

Ruslan Bes