1

I have defined a global variable in one of my template files page.php. I can access the global variables in my loop. But when the loop displays an individual post in single.php, the variable has no value. I defined the variable as global in my single.php.

What am I doing wrong?

1 Answer 1

0

Define it in functions.php, which is loaded on every request.

However, there are far better options than a global variable:

  • a function
  • a template part if it's a template you're defining
  • filters
4
  • I did define it in functions and I'm still not getting it.
    – LindaH53
    Commented Sep 10, 2017 at 20:04
  • @LindaH53 I'd strongly recommend against global variables, but remember that you have to tell PHP in a file that the variable is global, e.g. global $variable;, and if you don't PHP won't use the global variable.
    – Tom J Nowell
    Commented Sep 10, 2017 at 21:01
  • OK, thanks. I am putting it into a function. What's the reason for discouraging global variables? Thanks.
    – LindaH53
    Commented Sep 10, 2017 at 21:13
  • 2
    global state is an anti-pattern, and with global variables it's easy to accidentally overwrite other global variables from other code, or forget the global keyword. It also makes writing unit tests near impossible as the global variables provide hidden state the tests can't control
    – Tom J Nowell
    Commented Sep 10, 2017 at 22:57

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.