简体   繁体   中英

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.

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;

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM