Pass PHP variables between template files

If you need to pass a variable between template files, there will be many ways to do that. one more common way, not preferable way according to me is using Global variables.

For example you have instance of class, save it in Global variable and now you will be able to use it throughout the application.

GLOBALS['myobject'] = new class();

$wpdb, $wp_query are common global variables which WordPress use and these variable are accessible throughout the application. but what is the drawback of this method, these variable will be load at each page. as the number of variables increase, its become performance issue.

Another way you can use is using locate_template(). you can include that specific template file and then can use any variable which is existing in that file.


locate_template() will search in the STYLESHEETPATH before TEMPLATEPATH so that themes which inherit from a parent theme can just overload one file.

I mostly use templates to save in a folder and then using get_template_part() to get these small parts on WordPress generic template pages.

get_template_part( 'my-template-part' );

<?php get_template_part( 'templates/index', 'title' ); ?>


this function also makes it easy for a theme to reuse sections of code and an easy way for child themes to replace sections of their parent theme. you are all tempaltes are in one folder or may be subdivided to child folders. this will redurce a burden on generic templates by placing code into smaller pieces and also reuse.