WordPress.org

Ready to get started?Download WordPress

Forums

Where Can One Set a PHP Global? (4 posts)

  1. stevewilson
    Member
    Posted 2 years ago #

    It's a PHP question but I'm asking it here because the problem may have to do with the way WordPress apparently brings its modules in and out of existence. (I asked it in "Troubleshooting" but in the volume there it disappeared without a trace)

    The question is, where would one declare a global so that it will survive and be seen in functions.php? I have one function there that sets a global, then another that gets the current setting of the global, but when it goes to get, there nothing there. The setting has been lost.

  2. shazdeh
    Member
    Posted 2 years ago #

    Where are you setting the global? AFAIK, the functions.php file is the first file gets called after loading WP so make sure you are not reading it before setting it.
    One thing, this:

    $a = "Test";
    function func() {
       global $a;
       $a = "Whatevery";
    }

    fails and the value will still be what it was outside the function. What you should do is define the var like this:

    global $a;
    $a = "test";
    function func() {
       global $a;
       $a = "Whatevery";
    }
  3. stevewilson
    Member
    Posted 2 years ago #

    Shazdeh:

    Like you suggest, I declared the global as the first line of functions.php before any functions are defined. I then call function set_caller() to set $a's value, just as you show (on entering the Home page).

    If the reader then clicks on a post to "read more", single.php calls get_caller() to find out if the reader came from the home page. But $a is empty.

    I added $a = "test" right under global $a, just as you did. That was revealing, because now when I call get_caller() it says the value is "test". In other words, every time a function in functions.php is called, the global declared at the top is getting reset, destroying the value I had hoped to store.

    I think I'm going to have to create table in the database to freeze this property. Thanks for responding.

    Steve

  4. shazdeh
    Member
    Posted 2 years ago #

    Are you using something like this?

    if( is_home() )
    $a = true;

    because you see when you go to another page, function.php file get parsed again and the var would be empty. You can use $_SERVER['HTTP_REFERRER'] and check it's value, or use sessions to accomplish that.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags