- Remove slug from custom post type post URLs
- 14 Answers 14
- Plugin Roundup
- Remove post type slug in custom post type URL and move subpages to website root in WordPress
- Ryan Sechrest
- Remove “services” from the custom post type URL
- Add post type back to the post query
- Comments (95)
Remove slug from custom post type post URLs
It seems that all web resources based on the subject of removing a custom post type slug ie
are now very outdated solutions often referencing pre WP version 3.5 installs. A common one is to:
within your register_post_type function. This no longer works and is misleading. So I ask the community in Q4 2020.
What are the modern and efficient ways to remove the Post Type Slug from a Custom Post Type post’s URL from within the rewrite argument or anywhere else?
UPDATE: There seems to be several ways to force this to work with regex. Specifically the answer from Jan Beck should you be consistently willing to monitor content creation to ensure no conflicting page/post names are created. However I’m convinced that this is a major weakness in WP core where it should be handled for us. Both as an option/hook when creating a CPT or an advanced set of options for permalinks. Please support the track ticket.
Footnote: Please support this trac ticket by watching/promoting it: https://core.trac.wordpress.org/ticket/34136#ticket
14 Answers 14
The following code will work, but you just have to keep in mind that conflicts can happen easily if the slug for your custom post type is the same as a page or post’s slug.
First, we will remove the slug from the permalink:
Just removing the slug isn’t enough. Right now, you’ll get a 404 page because WordPress only expects posts and pages to behave this way. You’ll also need to add the following:
Just change «events» to your custom post type and you’re good to go. You may need to refresh your permalinks.
Write following code into the taxonomy registration.
Most important thing that you have to do after code changing
After you’ve altered your custom post type taxonomy document, try to go to Settings > Permalinks and re-save your settings, else you will get 404 page not found.
Looking through the answers here I think there is room for a better solution that combines some things I learned above and adds auto-detection and prevention of duplicate post slugs.
NOTE: Make sure you change ‘custom_post_type’ for your own CPT name throughout my example below. There are many occurrences, and a ‘find/replace’ is an easy way to catch them all. All of this code can go in your functions.php or in a plugin.
Step 1: Disable rewrites on your custom post type by setting rewrites to ‘false’ when you register the post:
Step 2: Manually add our custom rewrites to the bottom of the WordPress rewrites for our custom_post_type
NOTE: Depending on your needs, you may want to modify the above rewrites (disable trackbacks? feeds?, etc). These represent the ‘default’ types of rewrites that would have been generated if you didn’t disable rewrites in step 1
Step 3: Make permalinks to your custom post type ‘pretty’ again
NOTE: You can stop here if you are not worried about your users creating a conflicting (duplicate) post in another post type that will create a situation where only one of them can load when the page is requested.
Step 4: Prevent duplicate post slugs
NOTE: This will append the string ‘-duplicate’ to the end of any duplicate slugs. This code cannot prevent duplicate slugs if they already exist prior to implementing this solution. Be sure to check for duplicates first.
I would love to hear back from anyone else who gives this a go to see if it worked well for them as well.
I tried to figure this out not long ago and the short answer from what I know is no. Not from within the rewrite argument at least.
The long explanation becomes apparent if you look at the actual code of register_post_type in wp-includes/post.php line 1454:
You can see it prefixes $args->rewrite[‘slug’] to the %$post_type% rewrite tag. One could think «let’s just set the slug to null then» until you look a few lines up:
You can see that the function always expects a slug value that is not empty and otherwise uses the post type.
It’s almost 2020 and a lot of these answers don’t work. Here’s my own roundup of the current options:
- Matt Keys answer seems to be the only one on the right track if you want a custom code solution. None of the plugins I found can do everything listed here, especially the duplicate checking. This approach seems like a really good opportunity for a plugin if anyone wanted to take that on.
- Permalink Manager Lite
- 👍 Best of the free plugins I tried.
- 👍 Gives full control over all Page/Post/CPT complete permalink structure and allows them to be the same. The GUI is by far the most feature-rich.
- 👍 Allows full override per-post as well and lets you see what the original/default would be and reset to the default if needed.
- 👍 Supports multi-site.
- 👎 Does not check for duplicates between post types, which is sad. If a page and a CPT have the same URL, the page loads and the CPT is inaccessible. No warnings or errors, you just have to do your own manual checking for duplicates.
- 💵 All taxonomy features are in the PRO version. The upgrade nags are pretty heavy.
- Custom Permalinks
- 👍 The free version does a lot. Taxonomy permalinks and premium support seem to be the only things withheld from the pro version.
- 👍 Allows you to change the full permalink for any individual page/post/CPT.
- 👍 Supports multi-site.
- 👎 Does not allow you to change the default structure so you your Custom Post Types will still be example.com/cpt-slug/post-title but you can change them individually.
- 👎 Does not check for duplicates between post types, which is sad.
- Custom Post Type Permalinks
- 👍 Allows non-developer users to change the things that are easy to change already with register_post_type
- 👎 Does not allow you to change the CPT base slug — only the part that comes after that — so pretty much useless for developers and the issue in this question.
- remove base slug. — dead for several years now. do not use.
In response to my previous answer: you could of course set the rewrite parameter to false when registering a new post type and handle the rewrite rules yourself like so
You can see the add_permastruct call now doesn’t include the slug anymore. I tested two scenarios:
- When I created a page with the slug «calendar» that page is overwritten by the post type archive which also uses the «calendar» slug.
- When I created a page with the slug «my-event» and an event (CPT) with the slug «my-event», the custom post type is displayed.
- Any other pages do not work either. If you look at the picture above it becomes clear why: the custom post type rule will always match against a page slug. Because WordPress has no way of identifying if it’s a page or a custom post type that does not exist, it will return 404. That’s why you need a slug to identify either the page or CPT. A possible solution would be to intercept the error and look for a page that might exist similar to this answer.
Even after looking around everywhere, I couldn’t find a proper solution for removing CPT slug from permalinks that actually works and is consistent with how WordPress actually parses requests. As it seems, everyone else looking for the same solution is in the same boat as me.
As it turns out, this is actually a two-part solution.
- Remove CPT slug from permalinks
- Instruct WordPress on how to find posts from the new permalinks
The first part is quite straightforward and many existing answers already have it right. This is what it looks like:
Now, the second part is where things get ugly. After solving the first part, your CPT permalinks don’t have CPT slugs anymore. But, now, the problem is WordPress doesn’t know how to find your posts from those new permalinks because all it knows is CPT permalinks have CPT slugs. So, without a CPT slug in the permalink, it can’t find your post. That’s why when you make a request for your posts at this point, it throws a 404 not found error.
So, all you need to do now is instruct WordPress on how to find your posts using the new permalinks. But this is the part where existing answers don’t do very well. Let’s take a look at a few of those answers for example:
The below function works pretty well but it will only work if your permalink structure is set to Post name.
The below function works well for your custom post type regardless of the permalink structure however it will throw an error on all other post types.
There is another answer that is supposed to work as a standalone solution but ends up causing more issues than solutions like throwing errors in your CPT posts as well as on others. This one requires modifying the rewrite argument in your CPT registration as follows:
So far, all the existing answers I found are like the above ones. Either they work partially or don’t work anymore. This is probably because WordPress doesn’t give a streamlined way to remove CPT slug from custom post type permalinks and therefore these answers are either based on considering particular scenarios or based on a hacky way.
Here is what I have come up with while trying to create a solution that works on most if not all scenarios. This will properly remove CPT slug from CPT permalinks as well as instruct WordPress on finding CPT posts from those new permalinks. It doesn’t rewrite rules in the database so you won’t need to resave your permalink structure. Besides, this solution is consistent with how WordPress actually parses requests to find posts from permalinks which helps make it a more acceptable solution.
Make sure to replace custom_post_type with your own custom post type name. It appears once in every function so two occurrences in total.
This solution intentionally leaves out Plain permalink structure from its scope as it isn’t one of the pretty permalink structures. So, it will work with all permalink structures apart from the Plain one.
As WordPress doesn’t automatically prevent creating duplicate slugs across different post types, you may find problems accessing posts having the same post slugs because of losing uniqueness in CPT permalinks after removing the CPT slugs. This code doesn’t include any functionality to prevent that behavior so you may want to find a separate solution to address that.
In case there is a duplicate permalink, this code will prioritize your CPT over others and therefore display the post in your CPT when requested.
Remove post type slug in custom post type URL and move subpages to website root in WordPress
I recently had a need to rewrite the URLs of all parent and child pages in a custom post type so that they appeared to live at the website root, but in reality, continued to live in a custom post type within their hierarchy.
- I have a page called Services that lives at domain.com/services .
- I have a custom post type called Services .
- I have Services post called Programming that lives at domain.com/services/programming .
- I have Services post called Web Development , that is a child of Programming , that lives at domain.com/services/programming/web-development .
- The Services page should remain where it is i.e. domain.com/services .
- The Programming post should appear to live at the website root i.e. domain.com/programming .
- The Web Development service should also live at the website root i.e. domain.com/web-development .
- Shorter URLs.
- Keep all website pages together.
- Keep all services together.
- Maintain hierarchy of services.
I have a custom post type setup like so:
Remove “services” from the custom post type URL
We’re going to use the post_type_link filter to do this.
Update 1/19/14: Tweaked function to work with WordPress installed in a subdirectory.
- Line 9: If $post is a valid post object.
- Line 13: If post belongs to a post type that we want to remove the post type slug from.
- Line 15: Build a new permalink from home URL with just the post name.
All of this will essentially give us URLs like this:
But neither of those will work – you’ll get a 404 error – because WordPress can no longer identify those posts as Services posts and therefore attempts to find pages called Programming and Web Development , which don’t exist, hence the 404 error.
If you take a look at WordPress’ rewrite rules:
You’ll see something similar to this:
As you can see, using the services slug, WordPress knows to take whatever comes after it ( (.+?) ) and pass it in as the pagename value ( $matches ), which translates to something like:
Since the first rewrite rule no longer applies (slug removed), it now passes programming in as the pagename without specifying the post type, and since this page doesn’t exist, WordPress can’t return the page.
Add post type back to the post query
Now that WordPress doesn’t know that it’s dealing with a custom post type, we need to provide it with this information. For that we’re going to use the pre_get_posts hook.
- Line 7: We’ll need the WordPress database object to get additional information about the post.
- Line 9-11: We’re going to make sure that the current query is the main query. Since a page can have multiple queries, we’re limiting our filter to only the query that gets information about the page itself.
- Line 13: We’re going to grab the pagename from the query, which might be programming or web-development .
- Line 15-20: Now we’re going to use the pagename to look in the database for that particular post and extract its post type.
- Line 22-23: If this post has a post type that we know we need to manipulate, we’ll need to perform additional actions.
- Line 24: We need to a create a query var for the post type and set it to the pagename , so WordPress knows where to actually find the data for the post.
- Line 25: We also need to set the post_type back to services .
- Line 26: In order for WordPress to load the right template i.e. single-services.php , we need to set is_single to true .
- Line 27: Last, but not least, we set is_page to false for good measure, since it’s a custom post type.
Update 9/20/13: Changed add_filter(‘pre_get_posts’, ‘custom_pre_get_posts’); to add_action(‘pre_get_posts’, ‘custom_pre_get_posts’);
Update: 12/23/14: As of WordPress 4.0, the code above doesn’t work. The following changes need to be made:
You’ve met all your goals. In addition, if you try to create a page with the same name as one of your services, you’ll notice that the slug (i.e. post_name , pagename , etc.) will now increment, avoiding a possible collision.
Here are a couple of things to keep in mind:
- I didn’t test the performance of this yet, but if you use some kind of caching system on your website, you should be fine.
- All my functions live within a PHP namespace, so I only prefixed them with custom_ for simplicity of this post.
- I’ve looked at many different solutions online, and they all had their fair share of problems, so this may too, I just don’t know it yet.
If you have questions or suggestions, leave them in the comments below.
Previously posted in WordPress and transferred to Ghost.
May 29, 2013 at 9:15 am
Thanks for the post! Unfortunately I can’t get it to work… I keep on getting 404s. Have tried updating the permalinks, flush_rewrite_rules(); , etc.
May 29, 2013 at 12:50 pm
First, I would output the current WordPress rewrite rules (example in post), just to make sure the ones you added are indeed active. Second, I would print out the $query variable ( print_r($query, true) ) in custom_pre_get_posts to see that the values are set to what you expect (and also make sure the code in the filter is executed).
July 7, 2013 at 8:34 am
Hi Ryanm thank you very much for this article. I’m going mad with this slug. I’ve tried your solution but it doesn’t work. Maybe you can help me – I have this situation:
– a custom type called “static”
– it’s hierarchical
– my permalink structure is: “/blog/%postname%”
– WordPress 3.5.2
Following your instruction everything works in admin side: I can create a “static” page called “My Page Title” and the permalink in the editor becomes “http://www.—.com/my-page-title”
Unfortunally, in the website I can reach this page only with the URL “http://www.—.com/blog/static/my-page-title”
I have tryed lots of solutions for DAYS!
July 11, 2013 at 8:36 am
When you go to the permalink that it’s supposed to be, what do you get? A page not found?
July 8, 2013 at 3:34 am
Man… as much as I want this to work its just not happening.
I’m trying to use this in combination with 301 redirects to create a short urls post type.
I didnt have the postype setup to begin with, so it took a minute to figure out I needed to add: add_action( ‘init’, ‘register_services’ ); May want to note this in the post.
Also, setting has_archive to true automatically adds it to your permalink structure, you show false .
My custom permalink structure is set to: /blog/%postname%/
So I was getting /blog/posttype/postname/
Shouldnt have mattered because you’re grabbing the last part of the path, but I think something was screwy there because when I print $post_name later in custom_pre_get_posts , it wasn’t finding anything.
Last resort, i think ill use http://wordpress.org/plugins/custom-permalinks/ and change them manually.
Thanks for trying though! Glad it worked for you.
July 11, 2013 at 8:48 am
Let’s systematically troubleshoot this. For step #1, let’s confirm the post_type_link filter is working. If you go anywhere in your template and use get_permalink($id) , with $id belonging to a services post, please provide the absolute path it printed out (you can omit the domain).
July 14, 2013 at 11:43 pm
To get this to work I had to change: $query->set(‘services’, $post_name); to: $query->set(‘name’, $post_name);
July 21, 2013 at 5:24 pm
July 30, 2013 at 8:16 pm
What are your thoughts about getting things running with WPMU, as of right now it would default the URL back to domain.com/services/ rather than domain.com/username/services/
July 31, 2013 at 9:30 pm
(1) You could wrap the filters in a is_main_site() check, which would only apply it to your main site, leaving your child sites as-is.
(2) In step 1, where you remove the “services” slug, you could perform a is_multisite() check and then parse $post_path accordingly, essentially accounting for the site name by keeping it in there or putting it back.
August 7, 2013 at 8:36 am
Will this work with WPML, too?
I’ve tried this plugin http://wordpress.org/plugins/remove-slug-from-custom-post-type/ but it only removes the slug for the main language…
August 7, 2013 at 8:55 am
I do have MU enabled on the site that I did this on, however, I’m only applying this code on the main site and not child sites, since don’t need it (yet). Looking at the code above, there is nothing to suggest that it wouldn’t work, except for, as Kevin pointed out, you may have to adjust the $permalink that’s created in step #1 when MU is installed as sub-directories instead of sub-domains, since there’ll be an extra component in the URL that needs to be accounted for.
September 19, 2013 at 2:38 am
Ryan, your tutorial was very useful. My case was similar to yours and I was able to remove the slug. But I made a few modifications for this to work as you can see here https://gist.github.com/stefanbc/6620151. First of all, this line
should be something like this
because according to the WordPress codex there is no filter pre_get_posts
And another thing I modified was this
This was my case. Thanks for the awesome tutorial.
September 20, 2013 at 10:03 pm
Thanks for the feedback, Stefan. You are right about it being an action and not a filter. I’ve updated my post above. With regard to pagename vs name , if your custom post type is based on a post, which is the default, name would be in fact the way to go, but if it’s based on a page, I think pagename is recommended. I’m actually using it as a page, but omitted that in my setup– thanks for catching that!
October 13, 2016 at 11:49 am
Your github code worked except that it was throwing a php error regarding variables. I changed:
chụp ảnh cưới
October 12, 2013 at 4:25 am
October 12, 2013 at 3:58 pm
The rewrite rules I showed were only a subset of those in the system to explain that particular point. What you have works just as well.
October 30, 2013 at 8:21 am
Sorry for asking – I couldn’t get where do I make the changes :$
October 30, 2013 at 8:38 am
You could put this in your theme’s functions.php file, however it would probably be best suited in a plugin. Take a look at the WordPress codex on how to create a plugin.
December 11, 2013 at 4:30 pm
Can I use your way for post-type pages also? I want to rewrite my URL structure from http://www.ex1.com/parentpage/childpage to http://www.ex1.com/childpage. So your code should work for me to. But it didn’t. Any idea why?
December 12, 2013 at 2:40 am
This code will not work on native post types, only custom post types.
December 30, 2013 at 3:59 pm
here is how i did:
register_post_type with these args
‘rewrite’ = array(‘slug’ => ‘/’,’with_front’ => false)
‘capability_type’ => ‘page’
using this approach there is no need to use post_type_link filter
then comes custom_pre_get_posts
December 30, 2013 at 9:27 pm
Thanks for sharing, Victor. I’ll try that out next time I’m working with that code!
January 12, 2014 at 10:55 am
Great article. THis seems to work for me on my sandbox site except one thing….
I have a main wordpress website at http://www.website.com, but I have an additonal wordpress install in a folder of the main website….so in other words, I have my live site here: http://www.website-name.com
but I installed another wordpress install in a folder I named DEMSO off that live site I use for sandbox stuff. http://www.website-name.com/demos/SANDBOX-SITE
I never have any problems, however when I am trying to use this code on the sandbox site, when I view the custom post type, it takes me back to the root wordpress install, so instead of the custom post type url being
http://www.website-name.com/demos/SANDBOX-SITE/post-name (the CPT slug is gone…yeah!!)
it is http://www.website-name.com/post-name
Can you recommend the code alteration so it doesnt strip it all the way back to the main website root, and instead takes it back to that particular wordpress install’s root?
January 13, 2014 at 2:38 pm
Bill, I revised the function to be a little more flexible and it should also now work with WordPress installed in a subdirectory. Take another look at the code in step 1.
January 18, 2014 at 7:02 pm
Thanks for the reply Ryan. I must be doing something wrong, because I cant get it to work. First, in step 1, you forgot the word custom in the function. Line 8 should be: function custom_post_type_link($permalink, $post, $leavename) <
But regardless, I tried this but it didnt work. Not sure if this matters or not, but the site is located in this path public_html/SUBFOLDER/the-wordpress-install-is-here
The custom post type name is “neighborhoods”. Here is my code:
January 19, 2014 at 5:36 am
You’re right, I didn’t test my quick update and it contained an error. Please take another look, this time tested, and it should now work for you.
January 19, 2014 at 6:43 am
Ok, I tried new code …the permalink does change int he editor screen …the slug is not there, but I get the 404. I tried resetting permalinks just to make sure there wasn’t an issue there with the 404, but still no dice.
I will paste what I have below for the CPT just in case it is something on my end…
January 19, 2014 at 6:34 pm
Here is the code I used for testing https://gist.github.com/ryansechrest/03b3caa9f12c2d70f7bc. Throw this code in wp-content/mu-plugins/remove-cpt-slug.php and create a parent and child service post. Let me know if you have the same issues as with your neighborhoods post type.
January 21, 2014 at 8:05 am
thanks Ryan. I followed your instructions…I still get a 404 for both service posts I create (one parent and one child)
January 21, 2014 at 12:24 pm
Maybe you have a different kind of WordPress configuration or a plugin that is preventing this from working? I downloaded WordPress 3.8, installed it in a subdirectory as a single site, and then only installed that plugin I referenced above, and that worked for me.
As a side note, this is also working on a production site running multisite, where WordPress is in a subdirectory, but served from the root.
The ultimate test would be to setup a clean WordPress, just to rule out a configuration/setup/plugin issue. If that works, you know it has something to do with your sandbox.
With regard to debugging the sandbox, since the problem seems to be related to step #2 (since the URL seems to be accurate), I would start with printing out various variables. Something like:
January 21, 2014 at 1:05 pm
Thanks for your help Ryan!
….I deactivated all plugins, and switched to 2014 theme…. still same issue. 404 error.
Here is my set up: I originally had a website in the main public_html folder. Then over the years, I added three add-on domains for this hostgator account. so it was set up like this:
public_html/MAIN WORDPRESS INSTALL/ (then I have three different folders here….one for each of the three add-on websites)
Each of the three folders has its own WordPress install. Then a year or so ago, I deleted the main wordpress install from the server because I dont use that site anymore…. but I kept the three ass-on websites….. so it looks like this
It’s the same public_html/ but with three different add-on domains, and the original wordpress install is not there anymore….just the addon folders. Not sure why this would make a difference, but maybe it does?
January 21, 2014 at 1:33 pm
The individual WordPress sites (using add-on domains) should be isolated from each other, so I don’t think that’s the problem.
Re: WordPress theme and plugin deactivation, while that is a good test, there could still be some configuration in the database that could prevent this from working. A better test would be a fresh install with a newly setup database.
Also, have you checked the output of the variables mentioned in my previous comment?
January 30, 2014 at 9:21 pm
Nice job. However I hope you can help.
I’m wondering what if you want to replace the post type slug with my taxonomy term slug. How do I do that?
January 30, 2014 at 10:49 pm
You could try something like this. It assumes you are using the post_tag taxonomy and only have one term. If you have more than one term, it will use the first one. In addition, while the permalink will generate based on your selected term, it doesn’t validate the term when parsing the URL, meaning the page would render with any term, really.
March 11, 2014 at 12:43 am
I am trying to change my cpt urls using your code. I could remove slug from parent post urls, but it fails on child post urls. My cpt is hierarchical. I modified the post_type_link hooked function as below and now it changes link for child pages as well
Now the permalinks are created correctly, but the problem is that i get a 404 on child posts. I have dumped the query on both parent and child posts and i have noticed that on child post, the query_var attachment is set and no other query_vars are set. Please help if possible. Thanks.
March 12, 2014 at 9:47 am
OK, first you’ll want to change post_title to post_name on line 10, because otherwise you might have space and capitalization issues in the URL. I’d also add the trailing slash.
Second, and this is the main problem, the post name being used to find your child page in the database contains the parent slug, in other words, parent-page/child-page , but there is no post with a post name like that, hence the page not found error.
That means you have to strip out the parent slug or simply take the contents after the last slash.
If you add the following after $post_name = $query->get(‘pagename’); in the pre_get_posts hook, it should work:
April 29, 2014 at 2:50 am
The Parent works well actually but the Child pages are giving me 404:
anything did I miss?
April 29, 2014 at 9:12 am
I don’t think you followed my tutorial very closely, because your code looks completely different. At first glance, though, I believe you’re coming up empty here:
Try swapping $query->query[‘name’] with $query->get[‘pagename’] .
January 13, 2015 at 6:51 am
thank you for this great post, it was exactly what I am looking for.
Just one question regarding to Tomas post if this function or plugin will work with WPML:
I use your function for a site which is published in two languages (German source and English using WPML plugin). I have different custom post types (on of them is members, not hierarchical) which are first filled in an overview page (simple loop) including an link to the detail page of the member. The overview works as expected but when I try to get the detail page it only works in the German version, the English version throws an error 404. I would really appreciate any advise which will point me to the right direction.
January 13, 2015 at 9:55 am
Looking back at Tomas’ post, I didn’t even realize that he was talking about WPML the plugin and not WPMU… I skipped right over that!
«I use your function for a site which is published in two languages (German source and English using WPML plugin).»
So your main site is example.org and your translated site is something like example.org/?lang=en , right?
«I have different custom post types (on of them is members, not hierarchical)»
So member pages look something like this, right?
«which are first filled in an overview page (simple loop) including an link to the detail page of the member»
When you say overview and detail page, do you mean something like:
Overview: example.org/members/john-doe — Contains picture, name, basic info.
Detail: example.org/members/john-doe/details — Contains expanded profile, posts published, etc.
«The overview works as expected but when I try to get the detail page it only works in the German version, the English version throws an error 404.»
But this does not:
Did I understand the problem correctly?
January 13, 2015 at 2:04 pm
thank you for your response.
No it is example.org/en and for german (source language) only example.org/
My german overview page has this url format: myurl.com/my-page/my-subpage/sub-sub-page/ with a list of all members.
It is a loop through the cpt (in the template file) with listing the members in this page showing their picture and small informations, including a link to their detail page.
The english version has this url: myurl.com/en/my-page-en/my-subpage-en/sub-sub-page-en/
What I do is using your function to remove the slug from cpt an add a new path to get the following result for the detail page in the url (german):
I have an if statement in the function to get the current language code and use to two different path for the german and english version.
Everything works perfect in the german version but when I try to call the detail page of e.g. myurl.com/my-page/my-subpage/sub-sub-page-en/john-doe I get the error 404.
Thank for your help and if you need more information please let me know.
January 13, 2015 at 2:52 pm
You have en several times in the URL, but that’s just to indicate that it is an English slug, right? The only thing used to determine language is en right after the domain, correct?
In other words, this works:
If so, it seems part 1, building the URL, is working fine for you, but you’re having trouble with part 2, which is rebuilding the query to then display the resulting data.
January 14, 2015 at 4:47 am
This is working
January 14, 2015 at 9:05 am
OK, can you post the code you’re using for part 2 with the modifications you made?
January 14, 2015 at 9:33 am
Here is the code I am using:
And the pre_get_post functions look like this:
It seems that the first function causes also an error in the backend, all page, post and cpt linstings disappeared this morning. By removing the function everthing works again.
January 14, 2015 at 2:21 pm
Can you print out $result on a German and an English error page? You can do that with something like:
«It seems that the first function causes also an error in the backend, all page, post and cpt linstings disappeared this morning. By removing the function everthing works again.»
Do you know what the error was?
January 15, 2015 at 8:05 am
I was wrong, it is not the first function, it is the pre_get_post function which causes the problem. After cache clearing the whole site throws an 404 error. It seems that in my case the first cpt mitglieder-svr is allways used in every query.
January 16, 2015 at 9:00 am
Give the original code a try for pre_get_posts (especially the query part that gets the post type), since you are not exactly doing what I’m doing in the blog post (which is writing all permalinks to the root without the post type slug).
February 2, 2015 at 6:46 am
I use your code but at step 2 it not working.
February 2, 2015 at 8:01 am
I want to few character to url example:
But step 2 not work. How can i fix it? and How can i add any character to my custom post type slug?
February 3, 2015 at 9:01 am
Let’s say your post name is “foobar” and let’s say you build a URL as follows:
When the query is performed to look up the post, there is no post in your database called “examplefoobar,” which is why step 2 is not working.
If you are adding “example” in the post name, you must remove it again prior to making the query. So, on line 8 in your first post, you could try something like this:
Note that in this case, regardless of where “example” occurs in the string, it will be removed, so depending on your rules, you may want to refine it.
Better yet, though, if you changed it to example/foobar instead of examplefoobar , that might be a little bit more reliable, as you could just grab everything after the last slash, but at that point, you might as well just change the slug of the post type to example , because then you don’t need any of this extra code.
You can find this argument in the rewrite section on the register_post_type page in the WordPress codex.
February 16, 2015 at 2:24 am
I have implemented your solution on my local environment, and it works like a charm. However, when i do the same on the online solution, some links break, and i cannot save stuff in the administration panel. (posts, permalinks and more). Any thoughts?
February 16, 2015 at 3:00 am
Nevermind Ryan, i seemed to fix the problem. The former programmer on the site im working on, made a bunch of whitespaces in the online version of the functions.php file, which caused the white screen of death.
thanks for the awesome solution
February 16, 2015 at 9:56 am
Good deal– glad it’s working for you!
February 17, 2015 at 2:13 am
Hello again, it seems i have found yet another problem :/
When i implemented your solution, i changed the permalinks to some of my custom post types, so that they linked to the root of the website. By doing that, i now have more than one link to my custom post types. The links i had before i changed it, is still active, and thats not good according to google (SEO), because the pages are interpreted as duplicates (obviously).
Any idea how to fix this?
May 28, 2015 at 4:48 am
Hi ryan, Trying to use your solution to remove “product” from slug in woocommerce
But the query in get is quite empty (at least for name and pagename) , and i got 404.
This is the code, in case you spot any issue…
August 29, 2015 at 3:17 pm
You are rock ryan… Its help me alot. In first try it was not working but now it working… Thank you so much…
November 12, 2015 at 9:57 am
DO you think is possible to just remove the cpt name from a slug, but keep the hierachy url ?
Your code work well, but as you need, also remove the hierachy
November 13, 2015 at 7:06 am
November 13, 2015 at 12:30 pm
Take a look at this Gist I put together– it should do the trick.
November 16, 2015 at 4:24 am
i think i‘ve found a first probleme $query->get(‘pagename’); return an empty string…
November 16, 2015 at 4:10 am
Thnaks a lot for your answer.
However i have a 404 error on my child page.
I create my CPT with the CPT UI plugin (so i remove your cpt definition in your plugin)
my CPT name is ‘galerie’ so i also remove all ‘service’ string by ‘galerie’ in you plugin.
November 16, 2015 at 7:36 am
i’ve spent time on the problem and here is what happen :
– i can’t get the post type in the pre_get_posts function because after apply the post_type_link filter,
$post_name = $page_name = $query->get(‘pagename’); is empty.
So here is what i’m done. this work but it’s really tricky
note: i also test the $page_id , because my home page is a custom template page.
on this page (home), the $post_name is also empty, but not his ID.
How to you think we can improve the things ?
November 16, 2015 at 9:02 am
Print out $query in pre_get_posts using something like:
And let me know what the result is.
You need to obtain the post type, otherwise your hook will fire on every request and for all post types, which will most likely break other aspects of WordPress.
Also, just to confirm, are you running the latest version of WordPress? I tested this with version 4.3.1 and a non-multisite install.
November 17, 2015 at 7:18 am
Here is the result.
For info, my child post name is CEP.
As you can see the query let appear it as an attachment, but i didn’t know why (this is not the case if didnt filter the permalink).
My WP version is 4.3.1
November 18, 2015 at 1:22 am
I see the attachment, and that doesn’t appear to be normal. My guess is that either your theme or a plugin is responsible for that. It’s difficult to troubleshoot without having more context. I ran my code in a brand new WordPress installation, so I know there was nothing interfering there.
That said, I would test the code in a brand new WordPress installation and then add your theme and plugins back, one by one, to isolate what might be causing this.
November 18, 2015 at 9:11 am
Ok. Thanks a lot for your help.
I will try to setup a news WP and see
November 18, 2015 at 9:25 am
Ryan, i‘ve just setup a new clean install of the last version of WP,
and active only one plugin ‘Custom Post Type UI’.
I’ve setup a new cpt with the hierachie param on.
I’ve the same result as you can see
November 18, 2015 at 9:38 am
I’ve made a new test :
removing custom Post Type UI and put directly your gist…same effect…
The cpt service is seen as an attachment
November 20, 2015 at 12:07 am
Can you confirm where you placed the statement in the code and which page you were trying to load when it printed that out?
November 20, 2015 at 7:20 am
I place it in the “pre_get_post” and i try to load
a child page of my cpt
November 20, 2015 at 8:27 am
Try putting it right before:
Also, when I was testing, I was using the Twenty Fifteen theme– which one were you using?
November 24, 2015 at 1:39 am
First at all thanks a lot for the timing you spending to help me.
So it’s really stange.
I’m also woth the twenty Fifteen theme.
After putting the die just before $query, this work well.
So i ‘ve donwload Custom Post Type UI, set another type and change the Git.
After this done, any thing work as except.
I’ve got an 404 on my custom type
And for the cpt “Services” (which work well before), i’m falling with the ‘attachment problem’ even if i remove the CPT plugin…
sorry for my poor english i’m french.
thanks a lot
November 24, 2015 at 1:45 am
Here the modified git i use
April 6, 2016 at 7:15 am
I’ve been trying to get this to work and in hope to find a solution, I also came across this before yours ( http://kellenmace.com/remove-custom-post-type-slug-from-permalinks/ ) which works, but not on a multisite install it would seem ( just on the main site ), so I continued to look for help and came here. I saw that you said your solution should work on a multisite install, so I thought ‘great!’, but I’ve been trying to get this to work for a little while now, and keep getting a 404 error.
I have a series of cpt’s that I want to do this with ( ‘excursion’, ‘hotel’, ‘offer’, ‘tour’ ), I have these setup on a multisite install of WP using subdomains. I have also got domain mapping on them, but I have tried your solution first without this active, but with no joy.
April 6, 2016 at 9:29 am
Does my code work for you on the first site in a multisite environment and just not on the other sites, or does it not work at all?
April 7, 2016 at 2:55 am
It doesn’t seem to work at all. On the main site the custom_post_type_link function seems to work as the url has those parts removed. But the custom_pre_get_posts function doesn’t seem to work as I get a 404.
On the other sites of the install it doesn’t do anything at all, the pages load without removing the parts and therefore load as ‘normal’.
April 7, 2016 at 10:30 am
Just to be sure, can you visit the Permalinks page to flush your rewrite rules and then see if you still get a 404?
April 8, 2016 at 7:30 am
April 8, 2016 at 8:58 am
If it helps these are my CPT & Taxonomies
April 8, 2016 at 9:28 am
but it doesn’t show anything, but if I change your code to match Colir’s version here …
it returns as banner, so is it the query here that is the issue?
April 8, 2016 at 4:18 pm
I took your code, with a minor tweak in labels:
«rewrite» => array( ‘slug’ => ‘holiday-type’, ‘with_front’ => true ‘hierarchical’ => true ),
You’re missing a comma after the true before ‘hierarchical’ .
Then I took all of my code above, with the revised version from 12/23/14, which basically is this:
I pasted it into a functions.php file on a multisite I’m running, and added multiple tours to two different sites. Each permalink had the post type removed and I saw each tour page render (using the default template).
There must be something else you have tweaked or installed that is interfering with the code above, but based on what you posted, I can confirm that it works.
April 15, 2016 at 10:42 am
Odd. Could domain mapping be causing the issue do you think?
April 15, 2016 at 11:10 am
Is that a plugin or are you doing it manually? The site network I tested it on actually uses a top-level domains for each site (as apposed to subdomain or subdirectory), so that does work as well.
April 15, 2016 at 11:30 am
If it’s not that, then the only other thing I can think of that might be causing the issue is the WPML plugin that allow the client to translate their website.
April 15, 2016 at 2:17 pm
I could definitely see WPML causing issues, since it manipulates database queries. I run a network of sites with WPML, but I don’t remove post type slugs on any of those sites. You might deactivate both the domain mapping and WPML plugin to see if that resolves the issue. If so, then at least you know where to look to find a workaround.
April 26, 2016 at 9:50 am
Thank for you post. It’s very useful.
But I was faced with another problem. I want to change woocommerce product url. Page returns a 404 error, and in WP_Query Object object i have
No relevant information. What it can be? It looks like the function is executed after construction of the post.
I would be grateful for any advice
April 26, 2016 at 11:38 am
Hi Alex! I don’t use WooCommerce, so I don’t have any information that would be helpful here. I will say that my tutorial is for changing the URL for post types that you register. Changing the URLs in post types registered by a third-party plugin might have unintended consequences.
January 19, 2017 at 1:47 pm
Awesome. One of the few solutions that work to get the URL’s right . Thank you
February 11, 2018 at 8:54 am
I am using WP 4.9.2 and I had to change:
$post_name = $query->get(‘pagename’);
to $post_name = $query->query[‘name’];
because the first one was always empty.
Maybe it could help somebody…
April 3, 2020 at 1:18 am
Yeah, same issue on WP. Plug-ins do help but slow down the page speed.
February 23, 2021 at 9:02 am
I hope that someone still keeps an eye on this post.
I have implemented the code above and I am able to rewrite the URL from
domainname.com/commerce/post-name to domainname.com/post-name
I gotta say this works excellent.
I am running into a problem. Everything works fine if I initially publish a post… the slug gets create and saved and the post is viewable.
The “Edit Permalink” button is gone.
When I save as draft, the slug does not get written and the permalink is empty.
Here is my code:
DECLARE CUSTOM POST TYPE
February 23, 2021 at 11:44 am
Hi Forbes, it looks like WordPress changed a few things since I published this. You could return the default permalink unless the post is published. So something like:
February 23, 2021 at 2:39 pm
Thank you Ryan. I will see if I can get this to work as expected.