Abhineet.in

unlearning the learnt

Menu
  • Home
  • About
  • CAT Preparation
Menu

How to change custom post permalink in WordPress

Posted on March 22, 2022April 5, 2023 by Abhineet Mittal

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.

Reference:

  1. https://wordpress.stackexchange.com/questions/369343/put-post-id-on-the-custom-post-type-url
Category: WordPress

Leave a Reply Cancel reply

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

Categories

  • Business
  • CAT Preparation
  • Coding
  • Fiction
  • Finance
  • How-To-Life
  • Javascript
  • Life
  • Life at Infosys
  • Photoshop
  • Productivity
  • Publishing
  • Social Awareness
  • Startup
  • Technology
  • Uncategorized
  • Utilities
  • Visual Studio Code
  • Web Development
  • WordPress
  • Work Culture

Recent Posts

  • The Ultimate Guide to CAT Preparation: Tips and Tricks
  • Self-Publishing vs. Traditional Publishing: Which Is Right for You?
  • 7 Effective Strategies to Overcome Procrastination and Achieve Your Goals
  • How to detect English/ASCII string in PHP
  • The state of automobile dealerships in India

Recent Comments

  • Rohan George on Intermediate, Stream & Location: Luck by Chance
  • Ashika on Intermediate, Stream & Location: Luck by Chance
  • Steve on My first job, Infosys
  • SAKTHI on Finally, its Mysore…
  • Akash dhyani Akash on Training Begins…
© 2023 Abhineet.in | Powered by Minimalist Blog WordPress Theme