Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dates in Custom post_type Permalinks in Wordpress 3.0

I'm adding a custom post_type to Wordpress, and would like the permalink structure to look like this:

/%post_type%/%year%/%monthnum%/%postname%/

I can't figure out how to add the date tags. Using this code, gives me /my_type/example-post-slug/:

register_post_type( 'customtype', array(
    ...other options...
    'rewrite' => array('slug' => 'my_type'),
));

How do I include the dates?

like image 613
Benj Avatar asked Jun 28 '10 22:06

Benj


2 Answers

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

like image 69
Sawny Avatar answered Sep 19 '22 01:09

Sawny


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.

like image 42
John Doe Avatar answered Sep 23 '22 01:09

John Doe