Maybe I simply do not understand what get_template_part()
is doing â¦
I have a file called event-list.php
that should work as template for other pages and files so all my events (a custom post type) get listed!
Inside this event-list.php
I have this â¦
<?php
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$wr_event_fields = get_post_custom();
$event_date_timestamp = $wr_event_fields['_wr_event_date'][0];
$event_date = strftime('%d.%m.%Y', $event_date_timestamp);
$event_time = $wr_event_fields['_wr_event_time'][0];
$event_speaker = $wr_event_fields['_wr_event_speaker'][0];
//get_template_part( 'event-item' );
?>
<!-- event-item.php -->
<div id="event-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="event-date"><?php echo $event_date; ?></div>
<div class="event_time"><?php echo $event_time; ?></div>
<div class="event-speaker"><?php echo $event_speaker; ?></div>
<div class="event-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<div class="event-description-excerpt"><?php the_excerpt(); ?></div>
</div>
<!-- event-item.php -->
<?php endwhile; ?>
So what I want to do is include another template inside of event-list.php
named event-item.php
which only holds the layout of an event. I want to use this event-item.php
maybe later also in different loops. It should just be the markup for each single event-item on my website. If I make a change inside of this even-item.php
template all “events” in any of my loops on my entire website should change.
The problem I have with this is the one in the above sample code.
I use get_template_part( 'event-item' );
to include the event-item.php
layout structure within my loop. And I get its custom post-meta outside of this template. However that does not work!
As you can see in my sample above I have to copy the entire layout structure from my event-item.php
inside of my event-list.php
so the post-meta stuff is filled in.
Any ideas what I don’t get here or what I’m doing wrong here?
Thank you in advance.
Matt
Try globalizing
$post
inside ofevent-item.php
.Also: be sure to call
wp_reset_postdata()
after you close your$loop
while loop.e.g.:
and then:
Edit
Assuming the problem is just the post meta data, I would suggest moving the post meta data variables inside
loop-item.php
. Only a guess, but perhaps your local variables aren’t getting passed through theinclude()
function that is part ofget_template_part()
.So, like this:
Also, to avoid
undefined variable
notices, you should define your variables usingisset()
conditionals; e.g. change this:…to this:
Instead of doing:
do this instead:
get_template_part
expects the filename will be:parameter1-parameter2.php
Also make sure that you declare the variables you want to use as globals, else they will be out of scope and not be shown: