admin管理员组文章数量:1122832
I am creating a custom WordPress theme and what I want is to define a global variable in theme file and call that variable in plugin files. I searched on google and many StackOverflow posts about this topic for instance :
creating function in the theme file
<?php
function ww_new(){
global $ww_new;
$ww_new = $post_slug;
}
add_action('wp_roles_init', 'ww_new');
?>
and call it in the plugin file
global $ww_new;
echo $ww_new;
but this approach doesn't work for me. Any clue regarding this?
I am creating a custom WordPress theme and what I want is to define a global variable in theme file and call that variable in plugin files. I searched on google and many StackOverflow posts about this topic for instance :
creating function in the theme file
<?php
function ww_new(){
global $ww_new;
$ww_new = $post_slug;
}
add_action('wp_roles_init', 'ww_new');
?>
and call it in the plugin file
global $ww_new;
echo $ww_new;
but this approach doesn't work for me. Any clue regarding this?
Share Improve this question edited Aug 29, 2020 at 6:49 Hector 6821 gold badge7 silver badges18 bronze badges asked Aug 29, 2020 at 6:08 JainJain 297 bronze badges1 Answer
Reset to default 1The most important thing about your problem is the loading priority. By default, Plugins are loaded before the theme. So, when you define a global variable in the functions.php
it is not available in plugins code like your example.
global $ww_new;
echo $ww_new;
But you can use the defined global variable if you make sure your code is running after defining it. It is possible by using hooks.
in functions.php
change the code to
function ww_new(){
global $ww_new;
$ww_new = $post_slug;
}
// Define it immediately after `init` in a high priority.
add_action('init', 'ww_new', 1, 1);
and then, in your plugin codes, you can use it like
add_action( 'init', 'ww_new_usage', 10, 1 );
function ww_new_usage() {
global $ww_new;
// Use the variable here.
}
Please read the $priority part of the add_action developer docs.
本文标签: phpDefine global variable in theme file and call that variable in plugin file
版权声明:本文标题:php - Define global variable in theme file and call that variable in plugin file 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736301812a1931306.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论