How to give a CPT (custom post type) a date based url

The question:

I have events that have an event-date custom field. I want to create a date based page to display all events for a given day, and my hope was to use the url to help with that.

I have a 7 day calendar working, and it shows a “featured” event for a given day. Then I want to link to a page that shows all the events for that day.

Not sure if this is at all possible but I figured the geniuses in this Stack would know.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Assuming that your event rewrite slug is event and you want your datebased URLs to look like: http://domain.com/event/2011-06-14/

function custom_permalink_for_my_cpt( $rules ) {
    $custom_rules = array();

    // a rewrite rule to add our custom date based urls
    $custom_rules['event/([0-9]{4}-[0-9]{2}-[0-9]{2})/?$'] = 'index.php?post_type=event&event-date=$matches[1]';
    return $custom_rules + $rules;
}
add_filter( 'rewrite_rules_array', 'custom_permalink_for_my_cpt' );

// add a query var so we can read the date passed in url
function my_custom_query_vars( $query_vars ) {
    $query_vars[] = 'event-date';
   return $query_vars; 
}
add_filter( 'query_vars', 'my_custom_query_vars' );

// modify the main wordpress query
function my_date_based_event_archives() {
    // only modify the wordpress query if its event archive and
    // we have got the event-date passed through the url
    if ( is_archive( 'event' ) && get_query_var( 'event-date' ) ) {
        global $wp_query;
        $meta_query = array(
            'meta_query' => array(
                array(
                    'key' => 'event-date',
                    'value' => get_query_var( 'event-date' )
                )
            )
        );
        $args = array_merge( $wp_query->query, $meta_query );
        query_posts( $args );
    }
}
add_action( 'get_template_part_loop', 'my_date_based_event_archives' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment