Date archives for custom message types

I have seen many questions / posts about this, but have not yet found a decent solution. I'm basically trying to do what it does wp_get_archives, but for a custom message type (personally, I'm not sure why it wp_get_archivesdoesn't support custom message types!).

The code I use is as follows

functions.php

function Cpt_getarchives_where_filter( $where , $r ) {
  $post_type = 'events';
  return str_replace( "post_type = 'post'" , "post_type = '$post_type'" , $where );
}

sidebar-events.php

add_filter( 'getarchives_where' , 'Cpt_getarchives_where_filter' , 10 , 2 );
wp_get_archives();
remove_filter('getarchives_where' , 'Cpt_getarchives_where_filter' , 10 );

This code displays dates (for example, April 2014, March 2014), etc., and this is great, but clicking on the links goes only to 404. The URL created on each date is / 2014/04 /, however it should be something like / events / 2014/04 /.

"" URL-, archive-events.php, - , 404?

+4
1

, , , , wp_get_archive() post, - . , Wordpress , . , , . , get_archives_link. 'has_archive' => true register_post_type() , settings->permalinks 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

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

Source: https://habr.com/ru/post/1538715/


All Articles