从外部php文件获取WordPress变量无效
我在一个外部文件中有两个变量 function.php 现在如果我从index.php中回显它们 我只从从外部php文件获取WordPress变量无效,php,wordpress,Php,Wordpress,我在一个外部文件中有两个变量 function.php 现在如果我从index.php中回显它们 我只从$xstring获取值,而不是从$bottomID 我知道$bottomID是有效的,因为如果我在index.php文件中有它,它会回显一个值 我想不出有什么问题 有什么想法吗?我会在functions.php中编写一个函数,并在index.php中调用它 function get_id_xstring() { global $post; $return = array(
$xstring
获取值,而不是从$bottomID
我知道$bottomID
是有效的,因为如果我在index.php
文件中有它,它会回显一个值
我想不出有什么问题
有什么想法吗?我会在
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'];
如果您在
function.php
中设置了一个变量,该变量位于全局范围内,则该变量将在index.php
中可见,这只是因为它们加载在同一范围内,但并非对所有模板都可用。大多数模板都是由函数加载的,在PHP中,函数中使用的任何变量默认都限制在本地函数范围内,因此必须将变量显式定义为
在您的例子中,设置了变量,并且值是
false
(在index.php
中使用var\u dump(isset($bottomID));
),这是因为您使用了一个global$post
,它还不存在,作为get\u post\u meta()
函数中的参数,因此,该函数的返回值为false
它是否显示任何错误?没有一个错误我激活了错误消息。如果xstring工作,那么bottomid也应该工作?告诉我们更多细节?@ferozakbar是的,应该可以:)但是我想我需要把wordpress配置文件包含到我的外部页面中。我会试着回答你:)谢谢你@Danijel。这是非常有用的信息!
function get_id_xstring()
{
global $post;
$return = array(
'id' => get_post_meta( $post->ID, 'bottom', true ),
'xstring' => 'This is a string';
);
return $return;
}
$my_vars = get_id_xstring();
echo $my_vars['id']; // bottomID
echo $my_vars['xstring'];