I have one template file videos.php which has the following line of code in it (aswell as a load of HTML):

<?php get_template_part('loop', 'feed-videos' ); ?>

inside that template part, I have the following:

<?php $video = 'video-' . $post->ID; ?>
<?php get_template_part( 'include', 'modal-video' ); ?>

I would then like to be able to use the $video variable inside include-modal-video.php.

So at the top of include-modal-video.php I have:

<?php global $video; ?>

Further down that file, I have <h2>00: <?php echo $video; ?></h2>

But I get nothing output from that line of code. All I see is the following indicator of where the value should be


Can anyone see what Im doing wrong?

  • 2
    don't don't don't don't ever use globals Nov 28, 2016 at 14:42
  • 1
    What's stopping you from requesting the $post->ID from inside that template part?
    – socki03
    Nov 28, 2016 at 15:23
  • 1
    And to expand on my previous comment,, template parts are supposed to be independent containers. If you need to pass global they are not independent any more, therefor if you feel like you need to pass a global you most probably doing something wrong Nov 28, 2016 at 15:24
  • 1
    $post is just about the only global variable you need :)
    – socki03
    Nov 28, 2016 at 16:11
  • 1
    @pealo86, yes and wordpress is full of globals which makes wordpress core code ugly to read and understand. Use them if there is no other way. In your case, you can have a filter "called" in your template part and set an handler in the "including" code. maybe I should make this into an answer... Nov 28, 2016 at 16:12

2 Answers 2


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


Then, <h2>00: <?php echo $video; ?></h2> will work.


Since WP version 5.5, you can pass arbitrary data to get_template_part() for use in the template - see the other answer below from @Denis Fedorov


Wordpress 5.5

The $args parameter was added to get_template_part function. https://developer.wordpress.org/reference/functions/get_template_part/#changelog

Pass data

$data = [
  'video' => 'video-' . $post->ID,
get_template_part('include', 'modal-video', $data);


//handle passed arguments through $args
echo $args['video'];

include-modal-video.php (extract)

echo $video;

The possibility of passing additional arguments to the template was added to all the template functions that use locate_template in Wordpress 5.5:

get_header, get_footer, get_sidebar, get_template_part.

https://developer.wordpress.org/reference/functions/get_header/ https://developer.wordpress.org/reference/functions/get_footer/ https://developer.wordpress.org/reference/functions/get_sidebar/ https://developer.wordpress.org/reference/functions/get_template_part/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.