从外部php文件获取WordPress变量不工作


get WordPress variable from external php file does not work

我在一个外部文件中有两个变量

function.php

$bottomID   =  get_post_meta($post->ID, "bottom", true);
$xstring    =  "This is a string"; 

现在如果我从index。php

回显它们
echo $bottomID;
echo $xstring;

我只得到$xstring的值,而没有得到$bottomID的值

我知道$bottomID工作,因为如果我在index.php文件中有它,它会回显一个值。

我想不出是什么问题

任何想法?

如果你在function.php中设置了一个变量,它是在全局作用域中,变量将在index.php中可见,因为它们是在相同的作用域中加载的,但它不是对所有模板都可用。大多数模板都是由函数加载的,在PHP中,函数内部使用的任何变量默认情况下都局限于局部函数作用域,所以你必须显式地将变量定义为全局变量。

在您的示例中,设置了变量,值为false(在index.php中使用:var_dump( isset( $bottomID ) );进行测试),这是因为您在get_post_meta()函数中使用了尚未存在的global $post作为参数,因此该函数的返回值为false

我会在functions.php中编写一个函数,并在index.php中调用它。

function get_id_xstring()
{
    global $post;
    $return = array(
        'id'      => get_post_meta( $post->ID, 'bottom', true ),
        'xstring' => 'This is a string';
    );
    return $return;
}

index.php:

$my_vars = get_id_xstring();
echo $my_vars['id']; // bottomID
echo $my_vars['xstring'];