// remove cpt slug from permalinks
function remove_cpt_slug12( $post_link, $post, $leavename ) {

    if ( $post->post_type != 'service' ) {
        return $post_link;
    } else {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
        return $post_link;
    }
}
add_filter( 'post_type_link', 'remove_cpt_slug12', 10, 3 );


// instruct wordpress on how to find posts from the new permalinks
function parse_request_remove_cpt_slug12( $query_vars ) {

    // return if admin dashboard 
    if ( is_admin() ) {
        return $query_vars;
    }

    // return if pretty permalink isn't enabled
    if ( ! get_option( 'permalink_structure' ) ) {
        return $query_vars;
    }

    $cpt = 'service';

    // store post slug value to a variable
    if ( isset( $query_vars['pagename'] ) ) {
        $slug = $query_vars['pagename'];
    } elseif ( isset( $query_vars['name'] ) ) {
        $slug = $query_vars['name'];
    } else {
        global $wp;
        
        $path = $wp->request;

        // use url path as slug
        if ( $path && strpos( $path, '/' ) === false ) {
            $slug = $path;
        } else {
            $slug = false;
        }
    }

    if ( $slug ) {
        $post_match = get_page_by_path( $slug, 'OBJECT', $cpt );

        if ( ! is_admin() && $post_match ) {

            // remove any 404 not found error element from the query_vars array because a post match already exists in cpt
            if ( isset( $query_vars['error'] ) && $query_vars['error'] == 404 ) {
                unset( $query_vars['error'] );
            }

            // remove unnecessary elements from the original query_vars array
            unset( $query_vars['pagename'] );
    
            // add necessary elements in the the query_vars array
            $query_vars['post_type'] = $cpt;
            $query_vars['name'] = $slug;
            $query_vars[$cpt] = $slug; // this constructs the "cpt=>post_slug" element
        }
    }

    return $query_vars;
}
add_filter( 'request', "parse_request_remove_cpt_slug12" , 1, 1 );