繁体   English   中英

从外部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 (使用: var_dump( isset( $bottomID ) );index.php ),这是因为您使用了一个尚未存在的global $post作为get_post_meta()参数get_post_meta()函数,因此该函数的返回值为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'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM