Including an event date in the post slug

While events can have multiple dates, there is only one page for an event – and so an event date included in the url might not make much sense. But if you have a collection of events with the same name, or you only have single events: an url of the form events/event/my-event-2013-03-13 provides an unambiguous way to point to your event.

The following code hooks onto when an event is saved, it then uses the event title and the schedule start (for single events this just the date, for recurring events this is the first start date), to generate a unique slug (hopefully the title and date will make it unique enough!).

Be Careful of Infinite Loops

Below we define a function which is to be called whenever eventorganiser_save_event is fired (after an event is updated). But the function calls wp_update_post() to update the event with the new slug – and this in a roundabout way fires the eventorganiser_save_event (which fires our function…) – infinite loop!

To prevent this the function removes itself from the hook, updates the event, and then re-adds it self, neatly side-stepping the infinite loop. Note: when removing a hooked function the priority must match the priority used when adding (in this case, 15).

Heavy Handed?

There are some important disclaimers to be made here: every time you save the event the slug is regenerated. This can cause two issues:

  • You can’t manually alter the slug. Every time you do, the plug-in jumps in and ‘corrects’ it.
  • Let’s suppose for some reason the event title (or schedule start date) changes – this will cause the slug to change too – meaning the old url will 404! While WordPress will update its links, social media sites, or Aunt Debby’s bookmarks won’t.

To work-around the second issue, you could first check the event’s post status and only update the slug if it has not yet been published.

The Code

add_action( 'eventorganiser_save_event', 'my_include_date_in_event_slug', 15 );
function my_include_date_in_event_slug( $post_id ){

    //Prevent infinite loops!
    remove_action( 'eventorganiser_save_event', 'my_include_date_in_event_slug', 15 );

    //Get event & schedule start date
    $event = get_post( $post_id );
    $date = eo_get_schedule_start( 'Y-m-d', $post_id ); 

    //Form new slug and ensure it's unique
    $new_slug = sanitize_title_with_dashes( $event->post_title .'-'.$date );
    $new_slug = wp_unique_post_slug( $new_slug, $post_id, $event->post_status, $event->post_type, $event->post_parent );

    //Update post
        wp_update_post( array(
        'ID' => $post_id,
        'post_name' => $new_slug,
        ));

    //Re-add the function
    add_action( 'eventorganiser_save_event', 'my_include_date_in_event_slug', 15 );
}

Tutorial Suggestions


Got some topics you would like to see covered? Then get in touch...