Portekoi
Portekoi

Reputation: 1147

Wordpress : ShortCode and variable

I'm trying to get a value from a ShortCode into a variable for use it in my template file. How can i do that?

Here is my code :

In the post, the short code :

[reference_prix]1-214eddz[/reference_prix]

My plugin code :

$bl_reference_prix = "";
add_shortcode('reference_prix', 'get_blref_prix');
function get_blref_prix( $atts, $reference = null ) { 
    global $bl_reference_prix;
    $bl_reference_prix = $reference;
}

But $bl_reference_prix is still empty.

I've try with $GLOBAL[] but i've the same issu.

What is the best practice for get a value write by the user in a wordpress post and display (or use it) in the template file?

Upvotes: 0

Views: 548

Answers (2)

Portekoi
Portekoi

Reputation: 1147

I've do this and it's working now as :

//Plugin
function get_blref_prix( $atts ) {
    global $bl_plugin_refprix, $bl_plugin_refprix_up;
    // Attributes
    extract( shortcode_atts(
        array(
            'reference' => '',
            'up' => '',
        ), $atts )
    );

    $bl_plugin_refprix = $reference;
    $bl_plugin_refprix_up = $up;

}
add_shortcode( 'bl_refprix', 'get_blref_prix' );

In the template file (Important : After the function "the_content"!) :

while(have_posts()):the_post();
    echo the_content();
endwhile;

echo $bl_plugin_refprix;

In the Post :

[bl_refprix reference="123" up="456"]

Upvotes: 0

katpadi
katpadi

Reputation: 21

I think the best practice is to use the atts parameter.

// Add Shortcode
function get_blref_prix( $atts ) {

    // Attributes
    extract( shortcode_atts(
        array(
            'bl_reference_prix' => '',
        ), $atts )
    );
}
add_shortcode( 'reference_prix', 'get_blref_prix' );

The user of the shortcode will just have to do the following in the editor:

[reference_prix bl_reference_prix="some value by the user"]

And then maybe you can try using the Options API. Add and delete after use.

Upvotes: 1

Related Questions