WordPress.org

Ready to get started?Download WordPress

Forums

How to make a custom global variable available everywhere? (2 posts)

  1. nat3
    Member
    Posted 2 years ago #

    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!

  2. vtxyzzy
    Member
    Posted 2 years ago #

    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();

Topic Closed

This topic has been closed to new replies.

About this Topic