Home » Php » wordpress – How do I declare a global variable in PHP I can use across templates?

wordpress – How do I declare a global variable in PHP I can use across templates?

Posted by: admin April 23, 2020 Leave a comment


In wordpress, it calls header.php then whatever template name or the page requested. How can I declare a variable in my php header which I can then refer to in my other templates?

How to&Answers:

The answer pretty much depends what you need it for. If you are developing a theme and want to keep values constant through all files you can place them in functions.php in the theme directory, which is always loaded. Variables defined there should be available everywhere in the theme. This works if you distribute the theme.

If you want to modify an existing theme for your needs on your own installation, you can either put them in wp-config.php, as suggested, or (a cleaner method) you can create a child theme of the theme you want to change. This will keep it separate from the wordpress core and will prevent theme updates from overwriting your changes.

I just tried it using functions.php:


$variable = "value";


global $variable;
echo $variable;

works for me.


You can declare it like so (In functions.php):

global $domain;
$domain = 'http://www.mydomain.com/';

You can echo the domain of the WordPress site like this, though..

<?php bloginfo('site_url');?>


$url = site_url();
echo $url;

Or as a function, in functions.php

function displayMyDomain() {
  global $domain; // you probably don't actually need to set it global as it is a function
  $domain = 'http://www.domain.com/';
  echo $domain;

Then anywhere, use <?php displayMyDomain(); ?>


You can define them in wp-config.php file.

The config file is never updated so your WordPress installation will have those variables over time even if you update it.

  echo $domain;


Another way to define global consts in WordPress, if for best practice purpose you don’t want to add a variable to your WP-config (to keep it clean ?). And for some reasons your variable scope is not getting the global scope everywhere in your website.

You can simply use :

define( 'MY_VARIABLE', 'My Value' );

For more information about consts scope :


I think php session is one of the way to use as a global variable on WordPress.

1. Functions.php

if(!session_id()) {

2. Any .php file where you want set or get global variables

  • get variable

    if(isset($_SESSION['global_var'])) {
        $local_var = $_SESSION['global_var'];
  • set variable

    $_SESSION['global_var'] = "This is global var";