There are many examples on the Internet similar as your, but the problem is that although wp_get_archive()
will create a list of custom post type archives, the links still points to the default post type. This is because Wordpress do not generate rewrite rules for the archives of the custom post type, you will have to manually create them. Here is an example of how to generate rules for yearly, monthly, and daily archives. It also shows how to convert links with get_archives_link
filter. Be sure to add 'has_archive' => true
to register_post_type()
array of arguments and to flush the rewrite rules by visiting the settings->permalinks
page in admin.
functions.php
add_filter( 'getarchives_where', 'getarchives_where_filter', 10, 2 );
add_filter( 'generate_rewrite_rules', 'generate_events_rewrite_rules' );
function getarchives_where_filter( $where, $args ) {
if ( isset($args['post_type']) ) {
$where = "WHERE post_type = '$args[post_type]' AND post_status = 'publish'";
}
return $where;
}
function generate_events_rewrite_rules( $wp_rewrite ) {
$event_rules = array(
'events/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$' => 'index.php?post_type=events&year=$matches[1]&monthnum=$matches[2]&day=$matches[3]',
'events/([0-9]{4})/([0-9]{1,2})/?$' => 'index.php?post_type=events&year=$matches[1]&monthnum=$matches[2]',
'events/([0-9]{4})/?$' => 'index.php?post_type=events&year=$matches[1]'
);
$wp_rewrite->rules = $event_rules + $wp_rewrite->rules;
}
function get_archives_events_link( $link ) {
return str_replace( get_site_url(), get_site_url() . '/events', $link );
};
sidebar.php examples
add_filter( 'get_archives_link', 'get_archives_events_link', 10, 2 );
wp_get_archives( array( 'post_type' => 'events' ) );
wp_get_archives( array( 'post_type' => 'events', 'type' => 'yearly' ) );
wp_get_archives( array( 'post_type' => 'events', 'type' => 'monthly' ) );
wp_get_archives( array( 'post_type' => 'events', 'type' => 'daily' ) );
remove_filter( 'get_archives_link', 'get_archives_events_link', 10, 2 );