Upcoming Events Shortcode for an Events Post Type
Adds an [upcoming_events] shortcode that lists the next events by start date, skipping events that have already begun.
Opens WPIDE on
Code
add_shortcode( 'upcoming_events', function ( $atts ) {
$atts = shortcode_atts( array( 'limit' => 5 ), $atts, 'upcoming_events' );
if ( ! post_type_exists( 'event' ) ) {
return '';
}
$now = wp_date( 'Y-m-d\TH:i' );
$key = 'wpide_upcoming_' . md5( $atts['limit'] . get_option( 'wpide_events_ver', '1' ) . substr( $now, 0, 13 ) ); // Refreshes hourly.
$ids = get_transient( $key );
if ( false === $ids ) {
$ids = get_posts( array(
'post_type' => 'event',
'posts_per_page' => min( 50, max( 1, absint( $atts['limit'] ) ) ),
'meta_key' => '_event_start',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array( array( 'key' => '_event_start', 'value' => $now, 'compare' => '>=' ) ),
'fields' => 'ids',
'no_found_rows' => true,
) );
set_transient( $key, $ids, HOUR_IN_SECONDS );
}
if ( ! $ids ) {
return '<p class="upcoming-events-empty">No upcoming events.</p>';
}
$html = '<ul class="upcoming-events">';
foreach ( $ids as $id ) {
$date = date_create_immutable( (string) get_post_meta( $id, '_event_start', true ), wp_timezone() );
$when = $date ? '<time datetime="' . esc_attr( $date->format( DATE_W3C ) ) . '">' . esc_html( wp_date( get_option( 'date_format' ), $date->getTimestamp() ) ) . '</time> — ' : '';
$html .= '<li>' . $when . '<a href="' . esc_url( get_permalink( $id ) ) . '">' . esc_html( get_the_title( $id ) ) . '</a></li>';
}
return $html . '</ul>';
} );
add_action( 'clean_post_cache', function ( $post_id, $post ) {
if ( $post && 'event' === $post->post_type ) {
update_option( 'wpide_events_ver', (string) microtime( true ), false );
}
}, 10, 2 );
Notes
Reads the start date saved by the Event Details meta box snippet (_event_start). Use limit="10" to show more.
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.