How to remove parent slugs from child pages permalinks in Wordpress?

136 Views Asked by At

I remove them all right, but when I actually try to go to a page, there is a 404 error.

The code I have used ( variation of https://wordpress.stackexchange.com/questions/182006/removing-parent-pages-from-permalink#answer-313280 )

function my_pages_permalink( $link, $post_id) {
    $slugname = get_post_field( 'post_name', $post_id, 'display' );
    $slugname = $slugname."/";
    $link = untrailingslashit( home_url($slugname) ) . '.html';
    return $link;
}
add_filter( 'page_link', 'my_pages_permalink', 10, 3 );

What else should be done? Some add_rewrite_rule? What it may be like?

1

There are 1 best solutions below

2
JayDev95 On

You are attempting to add .html at the end but WordPress pages are dynamic and most of the time .php pages.

Also, you are using untrailingslashit but then adding the slash back in. The updated version below checks if the page has a parent. If it does, it constructs the permalink using the child page's slug without including the parent slug. If the page doesn't have a parent, the original permalink is returned.

function my_pages_permalink( $link, $post_id ) {
    $post = get_post( $post_id );

    if ( is_object( $post ) && $post->post_parent ) {
        $parent = get_post( $post->post_parent );
        $link = trailingslashit( home_url() ) . $post->post_name . '.html';
    }

    return $link;
}
add_filter( 'page_link', 'my_pages_permalink', 10, 2 );