Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable from get_template_part?

Tags:

php

wordpress

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.

like image 612
Rob Avatar asked Aug 04 '26 06:08

Rob


2 Answers

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;
like image 103
soju Avatar answered Aug 05 '26 22:08

soju


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'));
like image 32
err Avatar answered Aug 05 '26 21:08

err



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!