I'm new I need to put a value obtained from a function and put it in my shortocode function if you can help me thanks
$a=4; // value obtained from another function my_function($a); function my_function($i){ $a=$i+1; return $a; } add_shortcode( 'operation', 'my_function' );
I'm new I need to put a value obtained from a function and put it in my shortocode function if you can help me thanks
$a=4; // value obtained from another function my_function($a); function my_function($i){ $a=$i+1; return $a; } add_shortcode( 'operation', 'my_function' );Share Improve this question asked Jul 3, 2020 at 0:18 StymarkStymark 372 bronze badges
1 Answer
Reset to default 0I don't really understand what you're trying to do. Why don't you just call the function inside the shortcode handler? This looks more like general PHP question.
Say we have a variable in our functions.php
or wherever you define your shortcodes:
$another_var = doSomeFunctionThatReturnsData();
With modern anonymous functions, you can pass variables using the use
keyword.
add_shortcode('operation', function (array $atts, ?string $content, string $shortcode_tag) use ($another_var): string {
$out = 'The value of my variable is: ' . $another_var;
return $out;
});
With ancient named functions as callbacks, you can access a variable in the global scope (defined outside and "above" your callback) by bringing it into your local scope (inside the body of your callback) by using the global
keyword:
function shortcode_operation_handler(array $atts, ?string $content, string $shortcode_tag): string {
global $another_var;
$out = 'The value of my variable is: ' . $another_var;
return $out;
}
add_shortcode('operation', 'shortcode_operation_handler');
Those words before variable names are types for the parameters (more on those in the PHP documentation). The type after the semicolon (:
) in the function definition denotes its return type.
... or you can simply call the function inside your shortcode handler.