Frage

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?

War es hilfreich?

Lösung

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;
}

Andere Tipps

Follow this link http://codex.wordpress.org/Shortcode_API#Overview

When the_content is displayed, the shortcode API will parse any registered shortcodes such as "[myshortcode]", separate and parse the attributes and content, if any, and pass them the corresponding shortcode handler function. Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself.

So all shortcode function must be return, you can change your function "wanted" to this:

function wanted(){
    return "wanted";
}

Using Ruslan Bes' answer, the code looks like this:

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;
}

add_shortcode( 'simplenote', 'shortcode_fn');

function wanted(){
    echo "wanted";
}

The WordPress standard way would be to provide two functions. One, get_wanted() would return the wanted string; the other, wanted(), is just:

function wanted() {
    echo get_wanted();
}

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() versus get_the_title().

As @Ruslan mentions, the most standard way without rewriting your existing function to build a string would be to use output control.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top