0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok but how i get the value in my template file?
By using Options or Transients API.
Options is not good for me because in don't want to use the database... just transmit the value.
thanks for your help. I've take your example and add my solution with global variable.
0

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.