custom post types, wp_get_archives and add_rewrite_rule

Custom post types do not have date-based archives by default (by which I really mean they don’t have permalink structures for their date archives). For example:

www.example.com?post_type=journal&year=2012&monthnum=4

should give you the archive of journals published in April 2012. However,

www.example.com/journal/2012/04

will probably give you 404 because it doesn’t exist as a re-write rule. You need to add them:

add_action('init', 'wpse50530_journal_archive_rewrite');
function wpse50530_journal_archive_rewrite(){
   add_rewrite_rule('^journal/([0-9]{4})/([0-9]{2})/?','index.php?post_type=journal&year=$matches[1]&monthnum=$matches[2]','top');
   add_rewrite_rule('^journal/([0-9]{4})/?','index.php?post_type=journal&year=$matches[1]','top');
}

will give you the month and year archives. (Please note the above is completely untested). You will need to flush the rewrite rules once after adding this (visiting Settings > Permalink).

Leave a Comment