2

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

00

Can anyone see what Im doing wrong?

  • 2
    don't don't don't don't ever use globals – Mark Kaplun Nov 28 '16 at 14:42
  • 1
    What's stopping you from requesting the $post->ID from inside that template part? – socki03 Nov 28 '16 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 – Mark Kaplun Nov 28 '16 at 15:24
  • 1
    $post is just about the only global variable you need :) – socki03 Nov 28 '16 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... – Mark Kaplun Nov 28 '16 at 16:12
4

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

include(locate_template('include-modal-video.php'));

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.