I will use an $variable who is outside the function. In the shortcode function.
This is what i will do:
function shortcodevariable( $atts ){
return 'echo $variable';
}
add_shortcode('variable', 'shortcodevariable');
I think we need an array but I dont now how, can somebody help?
Thank you very much.
I will use an $variable who is outside the function. In the shortcode function.
This is what i will do:
function shortcodevariable( $atts ){
return 'echo $variable';
}
add_shortcode('variable', 'shortcodevariable');
I think we need an array but I dont now how, can somebody help?
Thank you very much.
If you're using PHP > 5.3, then you can use a closure on the the_content
filter. This filter needs to be added after the $variable
has been defined and before the the_content
filter has fired.
add_filter( 'the_content', function( $content ) use ( $variable ) {
return str_replace( '[variable][/variable]', $variable, $content );
} );
Shortcodes are process by core on the_content
hook at a priority of 11. So any priority 10 or less will be run before that. If you want the callback to be run before wpautop
, use a priority less than 10.
There's no reason to add_shortcode()
because this code replaces the shortcode with the variable before do_shortcode()
is run.
Filters should ideally be placed in the themes functions.php file, but if for some reason $variable
isn't available to functions.php, then this little hack should work.
I just discovered the solution to use external variables within shortcodes.
function show_shortcode_variable(){
global $variable;
return $variable;
}
add_shortcode('variable', 'show_shortcode_variable');
So if your $variable = "foo";
and someone types this in Wordpress:
[variable]
... Then they'll see this output on their page or post:
foo
Your code is mostly okay, but you don't need the echo
at the end, and you need to define the variable as global
within the function.
Does that help?
You have missing shortcode_atts
and passing arguments in a shortcode. E.g
function shortcodevariable( $atts ){
$data = shortcode_atts( array(
'attribute-1' => '',
'attribute-2' => '',
), $data );
return $data['attribute-1'];
}
add_shortcode('variable', 'shortcodevariable');
Usage
In a post, pages etc.
[variable attribute-1='okay']
In php file
echo do_shortcode ( "[variable attribute-1='<?Php echo $variable; ?>']" );
Recently I have created the post Create a simple shortcode in WordPress.