How to change custom post permalink in WordPress

I have struggled with this issue for years. I tried different ways but they always felt like hacks and gave inconsistent results most of the time. I also tried a popular plugin which broke my site.

Whenever you add a custom post type in WordPress through code, there is no way to select a permalink structure for it. By default, it’s permalink is of the format- post-type-slug/url-slug.

Though there are plugins to modify the permalink of a custom post type, surprisingly, I could not find solid way to do it through code. But finally, I found it.

In this post, I will show you that how you can modify the permalink of a custom post type with just a few lines of code.

For example, I have a custom post type named "event" and I want to add post id to the end of the permalink.

First, you need to change the rewrite rule for the custom post type. To do this, add following two lines just after the code where you registered your custom post type-

global $wp_rewrite;
$wp_rewrite->extra_permastructs['event']['struct'] = 'contest/%event%-%post_id%';

Now, use the filter hook to change the permalink like so-

add_filter( 'post_type_link', 'modify_permalink', 10, 2 );
function modify_permalink( $post_link, $post ) {
    if ( $post && 'event' === $post->post_type ) {
        return str_replace( '%post_id%', $post->ID, $post_link );
    return $post_link;

And that’s it. It was so simple. No need of any bloated plugin which may break your site and add needless overhead.

You can modify the above code to modify permalink based on your requirement.



By Abhineet Mittal

Abhineet is IIM Alumnus and Founder of popular Digital Publishing Platform, Sahityapedia. He is a technology enthusiast by hobby & an avid reader.

Leave a Reply

Your email address will not be published. Required fields are marked *