首页 > 解决方案 > Pass variable from header.php to functions.php

问题描述

I have function in functions.php

function my_function() {
//do something
}

but inside this function i need to check page template and i need to use is_page(), or is_home() but in functions.php it didnt't work.

I can check page template at header.php, for example:

if (is_page(7)) :
$myVariable = 1;
else :
$myVariable = 2;
endif;

End it works at header.php, but now in functions.php in my_function i need something like this:

function my_function(){
if($myVariable == 1) :
//do something
else :
//do something else
endif;
}

I dont know how to pass this variable, or how to check page template in my function.

标签: phpwordpress

解决方案


您可以使用 global 关键字,如下所示。

if (is_page(7)) :
    $myVariable = 1;
else :
    $myVariable = 2;
endif;

function my_function(){
    global $myVariable;
    if($myVariable == 1) :
         //do something
    else :
         //do something else
    endif;
}

推荐阅读