WordPress 1 min read

How to Remove Parent Slug From Child Page URL in WordPress

Avatar for Ahmad Tahir By Ahmad Tahir

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.

Leave a Reply

Your email address will not be published.

Keep reading
Drag and Drop Sortable Rows in WordPress using jQuery UI

Drag and Drop Rows in WordPress Using jQuery

Introduction: As WordPress developers, we often find ourselves in situations where we need to create custom plugins to cater to the unique requirements of our clients. Recently, I encountered a challenge while developing a WordPress plugin for a client who required a user-friendly way to manage data through sortable rows with drag-and-drop functionality. Surprisingly, the […]

3 min read Read Guide