我想为页面设置一些特定的子页面;不管怎样;,我希望他们在site.url/whatever/child-page-name
我想做的是在加载过程中对页面进行优先级排序,以便;“随便什么”;存在请求的名称,应始终加载该名称(即使存在具有所述名称的CPT)。
如果子页面必须是页面(page
键入),然后可以使用parse_request
hook 有条件地更改请求类型,在您的情况下,请求类型是从自定义post类型请求更改为标准(子)页面请求,这意味着is_page()
将返回true,WordPress还将为以下页面加载正确的模板page-whatever.php
.
Working example, 尝试(&T);在WordPress 5.8.1上测试:
注:get_page_uri()
用于检索;“目录”;子页的路径,因此如果parent
是父页slug,并且child
是子页slug,则路径为parent/child
.
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 ] );
}
}
}