Support » Fixing WordPress » How to make a custom global variable available everywhere?

  • nat3


    I have some php code that needs to run on every page on my website. It checks for something in the URL and content in page bodies, widgets, and navigation menu needs to change a little based on the output of that code. Up until now I’ve just copied the php code (which has mysql queries) in every widget and page body, but I that’s really inefficient..

    The output of the code is in the form of variables, so nothing’s being “printed” out to the page or anything, but rather variables are being set, like $var1 = “somevalue,” so it’s the variables that I need to be available to the page body, widgets, and nav menu.

    I’ve tried putting my code in various files, like “header.php,” and using the output variables in the body/nav menu/ widgets by first saying:

    $global var1;
    echo “var1’s value: ” . $var1;

    But the value never is printed out, so it’s not working..

    Any recommendations as to where I should put this code?

    Thanks for your help!

Viewing 1 replies (of 1 total)
  • I think what you want is to put the code into a function in functions.php and call the function where ever you need it.

    Either declare the variables as global both inside the function and in the places you call it, or have the function return the values as an array. One way to do this:

    function testfunc() {
          return array(1, 'abc', 3);
       list($v1,$v2,$v3) = testfunc();
Viewing 1 replies (of 1 total)
  • The topic ‘How to make a custom global variable available everywhere?’ is closed to new replies.