0

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?

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.