Skip to content

Instantly share code, notes, and snippets.

@bagerathan
Created November 9, 2023 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagerathan/b6cfb289eee22c57f2aa1e4f7af18b1a to your computer and use it in GitHub Desktop.
Save bagerathan/b6cfb289eee22c57f2aa1e4f7af18b1a to your computer and use it in GitHub Desktop.
[Share slug between sub page and post type]
add_action( 'parse_request', 'my_parse_request' );
function my_parse_request( $wp ) {
$post_type = 'whatever'; // set the post type slug
// and the "whatever" below is the Page slug
// This code checks if the path of the current request/page URL begins with
// "whatever/" as in https://example.com/whatever/child-page-name and also
// https://example.com/whatever/child-page-name/page/2 (paginated request).
// We also check if the post_type var is the post type set above.
if ( preg_match( '#^whatever/#', $wp->request ) &&
isset( $wp->query_vars['post_type'], $wp->query_vars['name'] ) &&
$post_type === $wp->query_vars['post_type']
) {
$posts = get_posts( array(
'post_type' => 'page',
'name' => $wp->query_vars['name'],
) );
// If a (child) Page with the same name/slug exists, we load the Page,
// regardless the post type post exists or not.
if ( ! empty( $posts ) ) {
$wp->query_vars['pagename'] = get_page_uri( $posts[0] );
unset( $wp->query_vars['post_type'], $wp->query_vars['name'],
$wp->query_vars[ $post_type ] );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment