Learn how to remove a custom post type (CPT) slug from the URL using a WordPress code snippet.
To write this tutorial I was inspired by a question from a subscriber who wanted to remove the slug from his CPT.
In a previous tutorial I showed you how to create a plugin that registers a new Custom Post Type and also add categories (custom taxonomies) to it.
The slug for that CPT was defined this way :
rewrite' => array( slug' => __('porfolio', 'cg-cpt-portfolio' ),
So, if you go to the URL of a project, the address will be something like this:
Would you rather that the slug didn’ t show up in the URL?
Then you’re going to find out how to get it. But first…
ATTENTION: Touching WordPress permanent links can have unwanted effects.
Therefore, try to do the necessary tests to make sure that there are no URL collisions or side effects.
Instructions for removing a CPT slug from the URL
1. Modify the CPT slug
Change the slug of the Custom Post Type by substituting this:
You’re ready for the next step.
2. Modify the functions.php file
Add the following snippet to functions.php:
With this code snippet you tell WordPress that the CPT ‘portfolio’ has the same URL structure as the posts and pages on the web.
This way, you avoid a 404 error and the URL structure will be: https://yourwebsite.com/project-name/.
To make it work with other CPTs you just have to replace ‘portfolio’ with the one you want or add the name of a second Custom Post Type to the snippet.
3. Other considerations
To be able to see if the changes have taken effect, be sure to update the permanent links.
You have 2 ways to do this:
- Go to Settings > Permalinks and click “Save changes”.
- If you are using the CPT plugin made by code, you can also disable and re-enable it. This will update the links itself.
Now you know how to remove the slug of a custom post type from the URL.
Remember to always be very careful with the changes in the permalinks to avoid possible collisions between URLs.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉