There are 2 problems here
Problem 1: Scope
The missing piece of the puzzle is scope. Scope isn’t a WordPress thing, it’s a fundamental programming feature, to use a global variable in a scope you have to declare to PHP that it’s a global variable. If you use it somewhere else without declaring that it’s a global variable it’s a new and separate variable that has the same name.
Problem 2: Order and Timing Of Events
When you add your action based on the value of $my_global
the function has not happened yet. The code as it is written in your question requires time travel to work as is.
Remember:
- PHP programs are loaded from a blank slate for every request, you can’t assign a variable a value in one request, then read it in another. Some people think this is what
global
does but that’s not true.global
does not mean across your entire server, it only extends across that request being handled for that specific person at that specific time. add_action
tells WordPress “when this action/event happens, call this function”
With these things in mind the code should instead check at the time it’s needed if it should run, e.g.:
add_action( 'some_actionable_thingy', 'my_custom_function', 10, 4 );
function my_custom_function() {
global $my_global;
if ($my_global != 'yes') {
return;
}
// Do something here
}
Fundamentally though, global
variables are incredibly bad practice, make sites difficult to work with, and are unnecessary. You should avoid them as much as possible. At a minimum they should be replaced or wrapped with functions, if not superior methods.
How can I set global variables one time in functions.php and use it in custom plugins outside functions.
The code in functions.php
and in plugins are all loaded into the same place, WordPress doesn’t sandbox plugin code from each other, it’s loaded into a big giant melting pot along with WordPress itself.