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

1 Answer 1

Reset to default 1

The 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