Removing parent slug from URL on custom post type

In a quick test, I was surprised to find that this works out of the box. That is, the canonical URI for a child post still has the parent in the path, but the child post works just as well without it (doesn’t 404, doesn’t redirect). As a result, it should just be a matter of filtering post_type_link to get this to work as you’re asking! The following code should do just that:

function wpse_101072_flatten_hierarchies( $post_link, $post ) {
    if ( 'service' != $post->post_type )
        return $post_link;

    $uri = '';
    foreach ( $post->ancestors as $parent ) {
        $uri = get_post( $parent )->post_name . "https://wordpress.stackexchange.com/" . $uri;
    }

    return str_replace( $uri, '', $post_link );
}
add_filter( 'post_type_link', 'wpse_101072_flatten_hierarchies', 10, 2 );

Leave a Comment