# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: events, shortcode, calendar
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/upcoming-events-shortcode/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Upcoming Events Shortcode for an Events Post Type" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
