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.

$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.

 

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.

  • David

    Hello Naeem,

    I am reviewing your post but I am already doing this with the code and the variables are not being passed.

    I am gathering city and state from IP and want to feed form to automatically display the data for that location.

    I run the php to get the city and state information from the IP. Next I echo the variables and it is working. I go down in the form portion and the variables are not accessible.

    I am only wanting to run this ip geo decoding script on pages where I need the data.

    Any ideas why this isn’t working?

    • http://www.naeemrana.com/ Rana Naeem

      David,

      I am not very clear about your code and file structure. If your geo decoding script is included to page where your form exist. you must be able to use geo decoding data city, state etc..