Custom templates and date formatting

In this recipe we’re going to look at setting up a custom template for the [event_embed] shortcode and doing something interesting to the dates within that template. The scenario is roughly based on this forum thread, which can be summarized as follows:

  • Let’s say we have numerous long running (multi day) events such as one that runs from 10 December – 20 December
  • If today is 15 December, we want the start date to show as the 15th rather than the 10th

There are a few ways of approaching this, but we’re going to use a custom template for this recipe. Start by locating the default template used by the [event_embed] shortcode – you should find it in:

plugins/event-rocket/templates/embedded-events.php

Simply copy the contents of this file to:

themes/YOUR_THEME/tribe-events/embedded-custom-dates.php

To actually trigger the use of this custom template we need to tell the shortcode to use it. This can be done via the template attribute:

[event_embed template="embedded-custom-dates"]

The part of the template we are interested in changing is this line:

<div class="schedule"> <?php echo tribe_events_event_schedule_details() ?> </div>

It is actually possible to use a filter to modify the output of that function, but we’re going to keep things simple and do our work right in the template … naturally, if you prefer, you could break out the logic into a function and make it reusable.

This is our replacement code for the above section:

<div class="schedule">
	<?php
	// Date format to use throughout
	$format = get_option( 'date_format' );

	// We need to compare the start date with today's date
	$start = tribe_get_start_date( null, false, 'Ymd' );
	$now   = date_i18n( 'Ymd' );

	// If it started some days ago, make the start date appear as if it were today
	if ( $now > $start ) $start_date = date_i18n( $format );

	// Otherwise, if the event isn't starting until some future point, use it's
	// actual start date
	else $start_date = tribe_get_start_date( null, false, $format );

	// Let's put it together and print our modified event dates
	echo $start_date . ' – ' . tribe_get_end_date( null, false, $format );
	?>
</div>

Now, if an event started a number of days ago, the start date will appear as if it had only started today.