WordPress

How to Remove Parent Slug From Child Page URL in WordPress

November 27, 2023

In WordPress, the URL structure for child pages typically includes the parent page’s slug in the URL. For example, if you have a parent page with the slug “parent” and a child page with the slug “child,” the URL for the child page would be something like:

http://example.com/parent/child/

If you want to remove the parent slug from the child page URL, you can achieve this by using a custom function and modifying the permalink structure.

Add the following code to your functions.php file:

function custom_remove_parent_slug( $post_link, $post ) {
    if ( is_object( $post ) && $post->post_type == 'page' ) {
        $parent_post = get_post( $post->post_parent );

        if ( is_object( $parent_post ) ) {
            $post_link = str_replace( '/' . $parent_post->post_name . '/', '/', $post_link );
        }
    }

    return $post_link;
}
add_filter( 'post_type_link', 'custom_remove_parent_slug', 10, 2 );

function custom_rewrite_rules() {
    add_rewrite_rule(
        '([^/]+)/([^/]+)/?$',
        'index.php?pagename=$matches[2]',
        'top'
    );
}
add_action( 'init', 'custom_rewrite_rules' );

Go to your WordPress dashboard, navigate to “Settings” > “Permalinks,” and click the “Save Changes” button. This step refreshes your site’s permalinks.