[英]get WordPress variable from external php file does not work
I have two variables in an external file 我在外部文件中有两个变量
function.php function.php
$bottomID = get_post_meta($post->ID, "bottom", true);
$xstring = "This is a string";
now if I echo them from my index.php 现在,如果我从我的index.php回显他们
echo $bottomID;
echo $xstring;
I only get the value from $xstring
but not from $bottomID
我只从$xstring
获得值,但不从$bottomID
I know that $bottomID
works since if I have it in the index.php
file it echo out a value. 我知道$bottomID
有效,因为如果我在index.php
文件中有它,它会回显一个值。
Cant figure out whats the problem 无法弄清楚问题是什么
Any ideas? 有任何想法吗?
If you set a variable in function.php
it is in the global scope, variable will be visible in index.php
only because they are loaded in the same scope, but it is not available to all of your templates. 如果在function.php
设置变量,它在全局范围内,变量将在index.php
可见,因为它们在同一范围内加载,但并非所有模板都可用。 Most templates are loaded by a function, and in PHP any variable used inside a function is by default limited to the local function scope, so you must explicit define a variable as global . 大多数模板都是由函数加载的,而在PHP中,函数内部使用的任何变量默认都限制在本地函数范围内,因此必须将变量显式定义为全局变量。
In your case, variable is set and the value is false
( test with: var_dump( isset( $bottomID ) );
in index.php
), that's because you use a global $post
, that not yet exists, as parameter in the get_post_meta()
function, so the return value of that function is false
. 在您的情况下,设置变量并且值为false
(使用: var_dump( isset( $bottomID ) );
在index.php
),这是因为您使用了一个尚未存在的global $post
作为get_post_meta()
参数get_post_meta()
函数,因此该函数的返回值为false
。
I would write a function in functions.php
and call it in 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;
}
And in index.php
: 在index.php
:
$my_vars = get_id_xstring();
echo $my_vars['id']; // bottomID
echo $my_vars['xstring'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.