Variable scope in WordPress functions.php

What is the scope of variables you declare at the top of functions.php, outside of any of the individual functions?

This is a general PHP question…

Variables inside a function are only available inside that function.
Variables outside of functions are available anywhere outside of
functions, but not inside any function. This means there’s one special
scope in PHP: the global scope. Any variable declared outside of any
function is within this global scope. (read more)

Can that variable be read by any page with a hook to the function?

If the variable is declared as global, then yes.

Can one page set the variable and another page read it?

No, only one page is loaded per a loop. And each time you load a page the variable is “forgotten” unless you store it someplace. If you want to set variables, you’ll need to use a WP function such as update_option() and get_option(). This stores the variable in the database.

Leave a Comment