Upcoming Events List Shortcode (The Events Calendar)
Adds a [wpide_upcoming_events] shortcode that lists the next events from The Events Calendar with date, time and venue, for sidebars, landing pages and footers.
Opens WPIDE on
Code
add_shortcode( 'wpide_upcoming_events', function ( $atts ) {
if ( ! function_exists( 'tribe_get_events' ) ) {
return '';
}
$atts = shortcode_atts( array( 'number' => 5, 'category' => '', 'featured' => '' ), $atts, 'wpide_upcoming_events' );
$key = 'wpide_tec_upcoming_' . md5( wp_json_encode( $atts ) ) . '_' . (int) get_option( 'wpide_tec_ver', 1 );
$html = get_transient( $key );
if ( false !== $html ) {
return $html;
}
$args = array(
'posts_per_page' => min( 20, max( 1, absint( $atts['number'] ) ) ),
'start_date' => 'now',
'eventDisplay' => 'list',
);
if ( '' !== $atts['category'] ) {
$args['tax_query'] = array( array( 'taxonomy' => 'tribe_events_cat', 'field' => 'slug', 'terms' => sanitize_title( $atts['category'] ) ) ); // phpcs:ignore WordPress.DB.SlowDBQuery
}
if ( $atts['featured'] ) {
$args['featured'] = true;
}
$events = tribe_get_events( $args );
$html = '';
if ( $events ) {
$html = '<ul class="wpide-upcoming-events">';
foreach ( $events as $event ) {
$venue = function_exists( 'tribe_get_venue' ) ? tribe_get_venue( $event->ID ) : '';
$html .= sprintf(
'<li><a href="%1$s">%2$s</a><br><small>%3$s%4$s</small></li>',
esc_url( get_permalink( $event ) ),
esc_html( get_the_title( $event ) ),
esc_html( tribe_get_start_date( $event, ! tribe_event_is_all_day( $event->ID ) ) ),
$venue ? ' · ' . esc_html( $venue ) : ''
);
}
$html .= '</ul>';
} else {
$html = '<p class="wpide-upcoming-events-empty">' . esc_html__( 'No upcoming events right now.' ) . '</p>';
}
set_transient( $key, $html, 15 * MINUTE_IN_SECONDS );
return $html;
} );
add_action( 'save_post_tribe_events', function () {
update_option( 'wpide_tec_ver', (int) get_option( 'wpide_tec_ver', 1 ) + 1, false );
} );
Notes
Attributes: number (default 5), category (an event category slug) and featured="1". Results are cached for 15 minutes and cleared when an event is saved.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.