Variable use in get_template_part

As far as I understand (from the get_template_part codex) get_template_part is just a wrapper round the PHP require function.

So if I have a variable that I have create in a page template file e.g. $message, I would have assumed you could directly use that variable in the template part

Read More

So in template file:

<?php 
$message = 'my message';
get_template_part('messages'); 
?>

Then in template part messages.php:

<?php echo $message; ?>

However the echo will display nothing.

Related posts

Leave a Reply

3 comments

  1. If you use locate_template() instead of get_template_part() you can use all variables in that script:

    <?php include(locate_template('message.php')); ?>
    <?php echo $message; ?>
    

    Echo $message will work.