admin管理员组文章数量:1332383
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.
本文标签: phpShow data obtained from a function and place it in a shortocode function
版权声明:本文标题:php - Show data obtained from a function and place it in a shortocode function 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742295366a2448618.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论