Rob
Rob

Reputation: 6380

Get variable from get_template_part?

Is is possible to get a variable from another template?

I have a page template with the following at the top:

<?php echo $table_name; ?>

Then a bit further down the page I'm using this:

<?php get_template_part('governance-management'); ?>

Within that template is the following (along with lots of other code which shows fine):

<?php $table_name = "CPEL Implementation"; ?>

How can I echo out the $table_name variable in the first echo?

The problem is I'm calling a variable before it's set. Is there any way to get around that? I've tried putting the echo below the get_template_part but it still doesn't show anything.

Upvotes: 3

Views: 4108

Answers (2)

err
err

Reputation: 109

The "global" method didn't work for me. (As it is an accepted answer it maybe worked in 2012 but not in 2015?!)

I had to change the get_template_part line to this:

include(locate_template('content.php'));

Upvotes: 1

soju
soju

Reputation: 25312

Well, you simply have to declare your variable as global :

global $table_name;
$table_name = "CPEL Implementation";

If you want to use it in another template :

global $table_name;
echo $table_name;

Upvotes: 8

Related Questions