Custom Post Type slug same as page name causing a conflict
-
12-05-2021 - |
Frage
I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members).
If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template.
My Custom Post Type rewrite:
$rewrite = array(
'slug' => 'team-members',
'with_front' => false,
'pages' => false,
'feeds' => false,
);
This allows me to generate the proper URL of: http://www.example.org/team-members/bob-jones
The problem now is when I try to access the page: http://www.example.org/team-members/, it does not render the correct page template file (aptly titled page-team-members.php
). Saving permalink settings didn't work.
How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?
Lösung
What is appearing at http://www.example.org/team-members/ is the 'post type archive' for your post type. It's the automatically generated list of posts created by WordPress. If you don't want the post type to have an archive you can disable the archive by setting the has_archive
argument to false:
register_post_type( 'post_type_name', array(
'has_archive' => false,
) );
Now you can create a page at /team-members without a conflict.
Andere Tipps
I've found over the years that the easiest way to avoid this sort of conflict is to separate the CPT posts from the page by adding in an additional step in the URL.
For example, change 'slug' => 'team-members',
to 'slug' => 'team-members/member',
so your URL will become http://www.example.org/team-members/member/bob-jones
Sure, it's not ideal, and I'd rather the URL be cleaner, but sometimes you have to compromise for an easy life :-)