admin管理员组

文章数量:1122846

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']; 
}

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']; 
}
Share Improve this question edited May 4, 2018 at 14:49 Mayeenul Islam 12.9k21 gold badges85 silver badges169 bronze badges asked May 4, 2018 at 14:43 mage_entomage_ento 112 bronze badges 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
Add a comment  | 

1 Answer 1

Reset to default 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;

本文标签: GLOBALS39value139 is not working