简体   繁体   English

将变量从header.php传递给functions.php

[英]Pass variable from header.php to functions.php

I have function in functions.php 我在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. 但在这个函数里面我需要检查页面模板,我需要使用is_page()或is_home()但是在functions.php中它不起作用。

I can check page template at header.php, for example: 我可以在header.php检查页面模板,例如:

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: 结束它在header.php工作,但现在在my_function的functions.php我需要这样的东西:

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. 我不知道如何传递这个变量,或者如何在我的函数中检查页面模板。

you can use the global keyword as follows. 您可以使用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;
}

You can pass the variable into the function as a parameter like so: 您可以将变量作为参数传递给函数,如下所示:

function my_function($myVariable) {

    if($myVariable == 1) :
        //do something
    else :
        //do something else
    endif;

}

or you can declare $myVariable as a global variable like so: 或者您可以将$myVariable声明为全局变量,如下所示:

function my_function() {

    global $myVariable;

    if($myVariable == 1) :
         //do something
    else :
         //do something else
    endif;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM