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

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.

Read More

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

Related posts

Leave a Reply

1 comment

  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' );