1

My custom PHP script works on my PC over localhost. But, when I upload my code to the 'live' WordPress site, The $GLOBALS values are just null even they work on my localhost. (Nothing wrong with the database connection). Is the $GLOBALS not working on WordPress? My code is something like this one below:

$get_value = $db->query("SELECT * FROM mytable")->fetch();
$get_variable = $get_value['myvalue'];
function myfunction(){
   return $GLOBALS['get_variable']; 
}
1
  • maybe the place where you set the variable is not in a global scope then try $GLOBALS['get_variable'] = ... to set it.
    – mmm
    Commented May 11, 2018 at 18:29

1 Answer 1

0

The correct syntax for using with global keyword. To access a global variable in WordPress, you first need to globalize the variable with global $variable;

Write inside function.php as:

    function myfunction(){
       global $get_variable;
       $get_value = $db->query("SELECT * FROM mytable")->fetch();
       $get_variable = $get_value; 
    }

add_action( 'after_theme_setup', 'myfunction' );

Inside the function you can now able to any where. But, outside of this scope it needs to be re-declared as a global scope variable. Ex., to use inside single.php file, it will work as

global $get_variable;
echo $get_variable;

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.