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