最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Show data obtained from a function and place it in a shortocode function

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

I 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.

发布评论

评论列表(0)

  1. 暂无评论