4

The functions.php file for a theme contains functions, called by hooks, that could be called from multiple WordPress pages. The wp hook, for example, seems to be on every page. You can decide in each function with is_page() which page is calling and whether or not you want to execute the function for that page.

What is the scope of variables you declare at the top of functions.php, outside of any of the individual functions? Can that variable be read by any page with a hook to the function? Can one page set the variable and another page read it?

7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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