WordPress Snippets at WPcustoms

Custom post type yearly monthly archive permalinks

Assuming you have a custom post type called NEWS you can use permalinks like this yoursite.com/news/2014/10/ now – make sure you re-save your permalinks settings page to flush the settings.


/**
 * Snippet Name: Custom post type yearly monthly archive permalinks
 * Snippet URL: https://wpcustoms.net/snippets/custom-post-type-yearly-monthly-archive-permalinks/
 */
  function wpc_news_rewrite_rules(){

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

    add_rewrite_rule(
        'news/([0-9]{4})/?$',
        'index.php?post_type=news&year=$matches[1]',
        'top'
    );

}
add_action( 'init', 'wpc_news_rewrite_rules' );