我试图将我的$ _SESSION变量传递给WordPress的数据库查询函数。如果我在函数中定义$ _SESSION变量,它可以正常工作。但是当我在全局范围内定义它们并尝试传递它们时,它们不会通过。请查看以下示例。
这将转到下面的函数
$_SESSION['pages'] = $_POST['pages'];
但是当我补充说
$pages = $_SESSION['pages'];
$ pages不会传递给该函数。
$_SESSION['pages'] = $_POST['pages']; //passes
$pages = $_SESSION['pages']; //does not pass
function insertLocalBusinessSchema()
{
//include global config
include_once($_SERVER['DOCUMENT_ROOT'].'/stage/wp-config.php' );
global $wpdb;
// if I try to define this outside of the function it doesn't pass through.
$pages = implode(',', $_SESSION['pages']);
$paymentAccepted = implode(',', $_SESSION['paymentAccepted']);
$table_name = $wpdb->prefix . "schemaLocalBusiness";
$insert = "UPDATE ".$table_name." SET addressLocality = '".$_SESSION['addressLocality']."', addressRegion = '".$_SESSION['addressRegion']."', postalCode = '".$_SESSION['postalCode']."', streetAddress = '".$_SESSION['streetAddress']."', pages = '".$pages."', paymentAccepted = '".$paymentAccepted."' WHERE id = 1";
$wpdb->query($insert);
}
感谢您的帮助!
$_SESSION
是一个global variable
,所以你可以从你想要的任何地方调用它,而$pages
没有全局定义所以你需要将它作为参数传递给函数,如下所示:
function insertLocalBusinessSchema($pages)
{
echo $pages; // the variable is now in the function's scope
}
然后,您将调用传递$pages
参数的函数:
insertLocalBusinessSchema($pages);
如果你想在函数中使用变量$pages
而不将其值作为参数传递,你可以使用$GLOBALS PHP super global variable
这样做:
// super global variable GLOBALS
$GLOBALS['pages'] = $_POST['pages'];
function insertLocalBusinessSchema()
{
echo $GLOBALS['pages']; // this also works
}
更多here。
或者您可以像这样使用global
关键字:
$pages = $_POST['pages'];
function insertLocalBusinessSchema()
{
global $pages; // $pages becomes global
echo $pages; // this also works
}