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.
Preface
The situation:
- I have a page called
Services
that lives atdomain.com/services
. - I have a custom post type called
Services
. - I have
Services
post calledProgramming
that lives atdomain.com/services/programming
. - I have
Services
post calledWeb Development
, that is a child ofProgramming
, that lives atdomain.com/services/programming/web-development
.
The goal:
- 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
.
The reason:
- Shorter URLs.
- Keep all website pages together.
- Keep all services together.
- Maintain hierarchy of services.
Setup
I have a custom post type setup like so:
function register_services() {
$arguments = array(
'label' => 'Services',
'public' => true,
'capability_type' => 'page',
'hierarchical' => true,
'supports' => array('title', 'editor', 'page-attributes'),
'has_archive' => false,
'rewrite' => true
);
register_post_type('services', $arguments);
}
Solution
1. 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.
add_filter(
'post_type_link',
'custom_post_type_link',
10,
3
);
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'services':
$permalink = get_home_url() . '/' . $post->post_name . '/';
break;
}
return $permalink;
}
- 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:
domain.com/programming/
domain.com/web-development/
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:
echo '<pre>' . print_r(get_option('rewrite_rules'), true) . '</pre>';
You’ll see something similar to this:
Array
(
[services/(.+?)(/[0-9]+)?/?$] => index.php?services=$matches[1]&page=$matches[2]
[(.?.+?)(/[0-9]+)?/?$] => index.php?pagename=$matches[1]&page=$matches[2]
)
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[1]
), which translates to something like:
domain.com/index.php?services=programming
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.
2. 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.
add_action(
'pre_get_posts',
'custom_pre_get_posts'
);
function custom_pre_get_posts($query) {
global $wpdb;
if(!$query->is_main_query()) {
return;
}
$post_name = $query->get('pagename');
$post_type = $wpdb->get_var(
$wpdb->prepare(
'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1',
$post_name
)
);
switch($post_type) {
case 'services':
$query->set('services', $post_name);
$query->set('post_type', $post_type);
$query->is_single = true;
$query->is_page = false;
break;
}
}
- 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 beprogramming
orweb-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 toservices
. - Line 26: In order for WordPress to load the right template i.e.
single-services.php
, we need to setis_single
totrue
. - Line 27: Last, but not least, we set
is_page
tofalse
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:
$result = $wpdb->get_row(
$wpdb->prepare(
'SELECT wpp1.post_type, wpp2.post_name AS parent_post_name FROM ' . $wpdb->posts . ' as wpp1 LEFT JOIN ' . $wpdb->posts . ' as wpp2 ON wpp1.post_parent = wpp2.ID WHERE wpp1.post_name = %s LIMIT 1',
$post_name
)
);
switch($post_type) {
case 'services':
if ($result->parent_post_name !== '') {
$post_name = $result->parent_post_name . '/' . $post_name;
}
$query->set('services', $post_name);
$query->set('post_type', $post_type);
$query->is_single = true;
$query->is_page = false;
break;
}
Result
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.
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.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)
) incustom_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).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!
When you go to the permalink that it’s supposed to be, what do you get? A page not found?
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
totrue
automatically adds it to your permalink structure, you showfalse
.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 incustom_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.
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 useget_permalink($id)
, with$id
belonging to aservices
post, please provide the absolute path it printed out (you can omit the domain).To get this to work I had to change:
$query->set('services', $post_name);
to:
$query->set('name', $post_name);
Works great, thanks man!
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/
Cheers
kc
You have a couple options. (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 ais_multisite()
check and then parse$post_path
accordingly, essentially accounting for the site name by keeping it in there or putting it back.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…
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.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
to this
This was my case. Thanks for the awesome tutorial.
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!
@stefan
Your github code worked except that it was throwing a php error regarding variables. I changed:
to
and it worked beautifully.
Thanks
I using
[product-category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_cat=$matches[1]&feed=$matches[2]
[product-category/(.+?)/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_cat=$matches[1]&feed=$matches[2]
[product-category/(.+?)/page/?([0-9]{1,})/?$] => index.php?product_cat=$matches[1]&paged=$matches[2]
[product-category/(.+?)/?$] => index.php?product_cat=$matches[1]
[product-tag/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_tag=$matches[1]&feed=$matches[2]
[product-tag/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?product_tag=$matches[1]&feed=$matches[2]
[product-tag/([^/]+)/page/?([0-9]{1,})/?$] => index.php?product_tag=$matches[1]&paged=$matches[2]
[product-tag/([^/]+)/?$] => index.php?product_tag=$matches[1]
with htaccess?
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.
Sorry for asking – I couldn’t get where do I make the changes :$
Help? O:-)
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.Hi,
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?
thank you
efix
This code will not work on native post types, only custom post types.
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
Thanks for sharing, Victor. I’ll try that out next time I’m working with that code!
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?
http://www.website-name/demos/
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.
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:
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.
Hi Ryan…
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…
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 childservice
post. Let me know if you have the same issues as with yourneighborhoods
post type.thanks Ryan. I followed your instructions…I still get a 404 for both service posts I create (one parent and one child)
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:
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
public_html/website1.com or
public_html/website2.com or
public_html/website2.com
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?
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?
Hi Ryan,
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?
Cheers.
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.Hi Ryan,
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.
OK, first you’ll want to change
post_title
topost_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 thepre_get_posts
hook, it should work:Let me know if this works.
Hi Ryan,
I may need help on this:
http://pastebin.com/Qwaf8wuD
The Parent works well actually but the Child pages are giving me 404:
domain.com/parent1/weather
domain.com/parent2/weather
domain.com/parent2/weather
anything did I miss?
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']
.Hello Ryan,
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.
Thank you,
Yana
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!
So your main site is
example.org
and your translated site is something likeexample.org/?lang=en
, right?So member pages look something like this, right?
*
example.org/members/john-doe
*
example.org/members/jane-doe
*
example.org/members/foo-bar
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.So, this works:
*
example.org/members/john-doe
*
example.org/members/john-doe/?lang=en
*
example.org/members/john-doe/details
But this does not:
*
example.org/members/john-doe/details/?lang=en
Did I understand the problem correctly?
Hello Ryan,
thank you for your response.
No it is
example.org/en
and for german (source language) onlyexample.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):
and for the english version:
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.
Yana
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 isen
right after the domain, correct?In other words, this works:
But this does not work:
Did I get that right?
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.
Hello Ryan,
yes, exactly.
This is working
This is not working
Thank you
Yana
OK, can you post the code you’re using for part 2 with the modifications you made?
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.
@Yana
Can you print out
$result
on a German and an English error page? You can do that with something like:echo '<pre>' . print_r($result, true) . '</pre>';
Do you know what the error was?
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 cptmitglieder-svr
is allways used in every query.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.Hi Ryan
I use your code but at step 2 it not working.
This is my code:
Dear Ryan
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?
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 ofexamplefoobar
, 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 toexample
, 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.Hello Ryan,
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?
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
Good deal– glad it’s working for you!
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?
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…
You are rock ryan… Its help me alot,,, In first try it was not working but now it working… Thank you so much…
Hi.
DO you think is possible to just remove the cpt name from a slug, but keep the hierachy url ?
ex: http://www.domain.com/cpt-name/parent-post/child-post
to http://www.domain.com/parent-post/child-post
Your code work well, but as you need, also remove the hierachy
thanks
Hi. Thanks for this solution.
However, i can’t get a solution to keep the parent post name in the url
ex: http://www.domain.com/cpt-name/cpt-parent-page/cpt-child-page
to : http://www.domain.com/cpt-parent-page/cpt-child-page
any idea ?
thanks a lot
Hi Colir,
Take a look at this Gist I put together– it should do the trick.
i think i ‘ve found a first probleme
‘$query->get(‘pagename’);’ return an empty string…
Thnaks a lot for your answer.
The url is good: http://www.domain.com/parent_cpt_page_name/child_cpt_page_name
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.
Yo Ryan
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 thepost_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 ?
thanks
Hi Colir,
Print out
$query
inpre_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.
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
Hi Colir,
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.
Ok. Thanks a lot for your help.
I will try to setup a news WP and see
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
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
Hi Colir,
Can you confirm where you placed the statement in the code and which page you were trying to load when it printed that out?
I place it in the “pre_get_post” and i try to load
a child page of my cpt
Hi Colir,
Try putting it right before:
Also, when I was testing, I was using the Twenty Fifteen theme– which one were you using?
Hi Ryan.
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
Here the modified git i use
Hi Ryan,
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.
Can you help?
CODE
Hi Ash,
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?
Hi Ryan,
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’.
Just to be sure, can you visit the Permalinks page to flush your rewrite rules and then see if you still get a 404?
Yep already done that :/
If it helps these are my CPT & Taxonomies
I’ve tried adding
echo '$post_type: <pre>' . $post_type . '</pre>';
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?
Hi Ash,
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.
Odd. Could domain mapping be causing the issue do you think?
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.
Bugger.
It’s a plugin, this one https://wordpress.org/plugins/wordpress-mu-domain-mapping/
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.
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.
Hi, Ryan.
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 haveNo 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
Hi Alex! I don’t use WooCommerce, so I don’t have any information that would by 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.
Awesome. One of the few solutions that work to get the URL’s right !!!! Thank you
Hi Ryan,
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…
Yeah, same issue on WP. Plug-ins do help but slow down the page speed.
Greetings!
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
todomainname.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
REWRITE CODE
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:
Thank you Ryan. I will see if I can get this to work as expected.