Removing Parent Page(s) from Permalink

Similar questions have been asked before, but no answer suits well.

I have: site.com/parent-page/child-page
and would like to have: site.com/child-page

So I want to exclusively have permalinks with depth 1, without using the custom menu but still “hierarchizing” my pages in the admin all pages view and with parent/order in page attributes.

The solution also needs to work automatically, so not changing permalinks on each page with the plugin “Custom Permalinks”.

This is what I need, and I am sure it is possible with a few lines of code in the functions.php, which I have found elsewhere but only for posts to remove the category, but not working for pages to remove the parent.

This is such code, that maybe can be changed to work for pages?

add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename ) {
    $cats = get_the_category( $post->ID );
    if ( $cats ) {
        // Make sure we use the same start cat as the permalink generator
        usort( $cats, '_usort_terms_by_ID' ); // order by ID
        $category = $cats[0]->slug;
        if ( $parent = $cats[0]->parent ) {
            // If there are parent categories, collect them and replace them in the link
            $parentcats = get_category_parents( $parent, false, "https://wordpress.stackexchange.com/", true );
            // str_replace() is not the best solution if you can have duplicates:
            // example.com/luxemburg/luxemburg/ will be stripped down to example.com/
            // But if you don't expect that, it should work
            $permalink = str_replace( $parentcats, '', $permalink );
        }
    }
    return $permalink;
}

2 s
2

a quick search shows another stackexchange topic on this, and it used this code to cleanup the permalink of parents/ancestors:

function wpse_101072_flatten_hierarchies( $post_link, $post ) {
    if ( 'page' != $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 );

You can find that discussion here: Removing parent slug from URL on custom post type

Leave a Comment