How to use own php variables in wordpress template

2020-03-30 01:18发布

I am using a wordpress template in php like this:

<?php
include('wp-blog-header.php');
get_header();
?>

...Hello World...

<?php get_footer(); ?>

ok, it works good... but the contents of title and other meta tags are empty. How can I change the header contents or use my own $variables inside the get_header() section? it doesnt work like this:

$test="Blabla";
get_header();

.. inside a wordpress header template:
echo $test;

the $test variable is empty :(.. any ideas? thanks!

标签: php wordpress
4条回答
欢心
2楼-- · 2020-03-30 02:07

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

查看更多
我只想做你的唯一
3楼-- · 2020-03-30 02:12

Simply replace:

<?php 
$test="Blabla";
get_header(); 
?>

with:

<?php 
$test="Blabla";
include(TEMPLATEPATH . '/header.php');
?>;

and the variable will be in scope. Try to avoid using globals.

查看更多
ら.Afraid
4楼-- · 2020-03-30 02:13

By default get_header() pulls the header.php file. you could simply rewrite the header.php file to include what you want. If you don't want to rewrite it for all templates but for only a few you could use get_header('name') which would grab header-name.php in which you could have your own items.

查看更多
姐就是有狂的资本
5楼-- · 2020-03-30 02:18

put all your different custom function and/or variable in your functions.php

or replace get_header(); by include get_bloginfo("template_url").'/header.php';

查看更多
登录 后发表回答