How to use own php variables in wordpress template?

后端 未结 4 1216
孤街浪徒
孤街浪徒 2021-01-15 13:05

I am using a wordpress template in php like this:



...Hello World...



        
4条回答
  •  情歌与酒
    2021-01-15 13:38

    The $test variable is empty because the header is included by a function, hence effectively 'in' the function, and more importantly, in a different scope.. think of it like

    function get_header()
    {
      $test = '1234';
    }
    get_header();
    echo $test; // won't work because test is in a different scope
    

    you can however use globals, or $_SESSION variables, or create a static class to hold variables in that can be called from anywhere.

    the global option is probably the quickest fix here (not necessarily the strictest though).

    $GLOBALS['test'] = "Blabla";
    get_header();
    
    .. inside a wordpress header template:
    echo $GLOBALS['test'];
    

    hope that helps

提交回复
热议问题