Removing hierarchical pages in the permalink

I’d be curious if someone can find a better solution to this. Here’s what I came up with:

function wpse_91821_flatten_page_paths( $wp ) {
    if ( false !== strpos( $wp->matched_query, 'pagename=" ) && isset( $wp->query_vars["pagename'] ) && $wp->query_vars['pagename'] && false === strpos( $wp->query_vars['pagename'], "https://wordpress.stackexchange.com/" ) ) {
        if ( !get_page_by_path( $wp->query_vars['pagename'] ) ) {
            $page = get_posts( array(
                'name'        => $wp->query_vars['pagename'],
                'post_type'   => 'page',
                'post_status' => 'publish',
                'numberposts' => 1
            ) );
            if ( $page && isset( $page[0] ) ) {
                $wp->query_vars['pagename'] = get_page_uri( $page[0]->ID );
                $wp->request = $wp->query_vars['pagename'];
            }
        }
    }
}
add_action( 'parse_request', 'wpse_91821_flatten_page_paths', 5 );

What I’m doing here is intercepting parse_request and if it’s a pagename request, and the pagename doesn’t have a “https://wordpress.stackexchange.com/” in it, then I check to see if I can find a post with the correct name. If I find a page, I set the query var, which allows the rest of the request chain to proceed as normal, because WordPress thinks the request is the full hierarchical one.

You’d also want to add a filter to post_type_link so that your links are generated correctly (otherwise they’ll continue to be hierarchical).

Leave a Comment