Using Dates in Custom post_type Permalinks in Wordpress 3.0 Using Dates in Custom post_type Permalinks in Wordpress 3.0 wordpress wordpress

Using Dates in Custom post_type Permalinks in Wordpress 3.0


You can achieve this with the plugin Custom Post Type Permalinks. Just install the plugin and change the permalink format in the settings.


I have found a partial solution which allows for the permalink to be recognized and preserved upon loading the page in the address bar, but not updated in the edit screen or other links to the post on the site.Add the following to functions.php or a site specific plugin, replacing example-post-type with the identifier of your post type.

function example_rewrite() {  add_rewrite_rule('^example-post-type/([0-9]{4})/([0-9]{1,2})/([^/]*)/?','index.php?post_type=example-post-type&year=$matches[1]&monthnum=$matches[2]&name=$matches[3]','top');}add_action('init', 'example_rewrite');

This uses the Rewrite API documented hereTo find more tips on understanding the process see here.

One thing to bear in mind is no matter how you do this, it is impossible for two posts to have the same slug, even if they have different dates. This is because if the permalink scheme is ever changed, they could clash and cause errors.


You need to add WordPress structure tags to your rewrite attribute like so:

register_post_type('customtype',array(    ....    'rewrite' => array('slug' => 'customtype/%year%/%monthnum%','with_front' => false)));

Then add a post_type_link filter to rewrite the structure tags in your URLs for the custom post, so that the tags work:

function custompost_post_type_link($url, $post) {    if ( 'customtype' == get_post_type($post) ) {        $url = str_replace( "%year%", get_the_date('Y'), $url );        $url = str_replace( "%monthnum%", get_the_date('m'), $url );    }    return $url;}add_filter('post_type_link', 'custompost_post_type_link', 10, 2);

You can refer to this article for copypasta code (encapsulated in a class though) on creating custom posts like this. The article has a few extra bits of explanation and a few pieces of additional functionality too: https://blog.terresquall.com/2021/03/making-date-based-permalinks-for-custom-posts-in-wordpress/

EDIT: By the way, you'll also need to flush your permalinks after you're done for this to work.