avoid_blog_page_permalink_collision()
云策文档标注
概述
avoid_blog_page_permalink_collision() 函数用于在子目录安装的 WordPress 多站点中,防止站点 slug 与页面 permalink slug 发生冲突。它通过检查新页面名称是否与现有站点名称相同来避免子目录重复使用。
关键要点
- 仅适用于子目录安装的多站点环境,不适用于子域名安装。
- 仅处理页面(post_type 为 'page')的 slug 冲突检查。
- 仅在主站点(main site)上生效,且不检查有父页面的页面。
- 通过循环添加数字后缀(如 -2)来重命名冲突的 slug,直到找到唯一名称。
- 返回修改后的 post data 数组,确保 slug 唯一性。
代码示例
function avoid_blog_page_permalink_collision( $data, $postarr ) {
if ( is_subdomain_install() ) {
return $data;
}
if ( 'page' !== $data['post_type'] ) {
return $data;
}
if ( ! isset( $data['post_name'] ) || '' === $data['post_name'] ) {
return $data;
}
if ( ! is_main_site() ) {
return $data;
}
if ( isset( $data['post_parent'] ) && $data['post_parent'] ) {
return $data;
}
$post_name = $data['post_name'];
$c = 0;
while ( $c < 10 && get_id_from_blogname( $post_name ) ) {
$post_name = $data['post_name'] . '-' . ++$c;
}
if ( $post_name !== $data['post_name'] ) {
$data['post_name'] = $post_name;
}
return $data;
}注意事项
- 该函数自 WordPress 3.0.0 版本引入,是核心功能的一部分。
- 依赖 is_subdomain_install()、is_main_site() 和 get_id_from_blogname() 等函数来执行检查。
- 仅处理 slug 冲突,不涉及其他 permalink 结构或 SEO 优化。
原文内容
Avoids a collision between a site slug and a permalink slug.
Description
In a subdirectory installation this will make sure that a site and a post do not use the same subdirectory by checking for a site with the same name as a new post.
Parameters
$dataarrayrequired-
An array of post data.
$postarrarrayrequired-
An array of posts. Not currently used.
Source
function avoid_blog_page_permalink_collision( $data, $postarr ) {
if ( is_subdomain_install() ) {
return $data;
}
if ( 'page' !== $data['post_type'] ) {
return $data;
}
if ( ! isset( $data['post_name'] ) || '' === $data['post_name'] ) {
return $data;
}
if ( ! is_main_site() ) {
return $data;
}
if ( isset( $data['post_parent'] ) && $data['post_parent'] ) {
return $data;
}
$post_name = $data['post_name'];
$c = 0;
while ( $c < 10 && get_id_from_blogname( $post_name ) ) {
$post_name .= mt_rand( 1, 10 );
++$c;
}
if ( $post_name !== $data['post_name'] ) {
$data['post_name'] = $post_name;
}
return $data;
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |