You were getting /video-demos-tours/post-name
instead of /resources/post-name
because the following line in your theme_build_post_args
function is setting the rewrite slug to the post type slug (video-demos-tours
):
$args['rewrite']['slug'] = $slug;
So you should fix that, but as for how, that is up to you.
But then, although fixing that would give you the permalink structure you preferred (e.g. https://example.com/resources/video-post/
), visiting the URL of a post in the other CPT (resources
) would display a 404 error because the rewrite rules for video-demos-tours
now have a higher priority than the ones for the resources
CPT.
Therefore, you should actually use a different/unique rewrite slug which is not already in use by another post type.
resources/video-demos-tours
can be used, but the post type must be registered before theresources
CPT.
If, however, you must share the same rewrite slug between two or more of your CPTs, then one easy way without having to add custom rewrite rules, is by using the parse_request
hook like so:
add_action( 'parse_request', 'wpse418900_parse_request' );
function wpse418900_parse_request( $wp ) {
// Define the post types which share the same rewrite slug.
$post_types = array( 'resources', 'video-demos-tours' );
// If the URL path (i.e. $_SERVER['REQUEST_URI']) begins with /resources/
// as in https://example.com/resources/video-post/, then we'd modify the
// post_type value so that WordPress will "choose" from one of the above
// post types.
if ( preg_match( '#^resources/#', $wp->request ) &&
isset( $wp->query_vars['post_type'], $wp->query_vars['name'] ) &&
in_array( $wp->query_vars['post_type'], $post_types )
) {
$wp->query_vars['post_type'] = $post_types;
}
}
It worked well for me on my WordPress v6.3.1 site, but:
-
Remember that the solution will result in a slight overhead when loading the single post page.
-
The same slug (
post_name
) can be shared among posts in different post types, however, you would want to always use a unique slug with your posts if the post type is sharing the same rewrite slug.