[英]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.