I have created a custom post type called “product” using ‘Custom Post Type UI’ WordPress plugin and have created few pages using “product CPT” with assigning a parent.
Existing url structure is:
https://example.com/product/parent_url/child_url
I need to remove “product/” slug from the URL. Once I remove the “product/” slug from URL, it works fine when there is no parent added.
function remove_cpt_slug( $post_link, $post, $leavename ) {
if ( ! in_array( $post->post_type, array( 'product' ) ) || 'publish' != $post->post_status )
return $post_link;
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
When parent is there, it returns 404 (without /product slug).
Settings:
Hierarchical = True, Rewrite = True, Custom Rewrite Slug = ‘ ‘, With Front = False, Capability Type = page
Also I tried with changing ‘rewrite slug’ => ‘/’ and it makes it working fine for product CPT pages. But looks like it conflict with other permalinks and most of normal pages returns 404.
function custom_post_type_rewrite_rule($args, $post_type) {
if ($post_type === 'product') {
$args['rewrite'] = array(
'slug' => '/',
'with_front' => true,
);
}
return $args;
}
add_filter('register_post_type_args', 'custom_post_type_rewrite_rule', 999, 2);
Current permalink structure: https://example.com/%postname%
How can I keep “https://example.com/parent_url/child_url” for product pages without braking other permalinks..?