Passing variables to template parts
-
21-04-2021 - |
Pergunta
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?
Solução
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.
Outras dicas
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);
include-modal-video.php
//handle passed arguments through $args
echo $args['video'];
include-modal-video.php (extract)
extract($args);
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/