wp_normalize_site_data()
云策文档标注
概述
wp_normalize_site_data() 函数用于在将站点数据插入或更新到数据库之前进行规范化处理。它接收一个关联数组作为参数,并返回经过清理和格式化的数据数组。
关键要点
- 函数参数为 $data,是一个必需的关联数组,包含站点数据,具体字段可参考 wp_insert_site()。
- 返回值为数组,表示规范化后的站点数据。
- 主要功能包括:清理域名(domain)字段,移除非法字符;规范化路径(path)字段,确保以斜杠结尾;将网络ID(network_id)转换为整数;将状态字段(如 public、archived 等)转换为整数;以及处理空日期字段(如 registered、last_updated),若为空则移除。
- 函数内部使用 trailingslashit() 等 WordPress 核心函数辅助处理。
- 该函数自 WordPress 5.1.0 版本引入。
代码示例
function wp_normalize_site_data( $data ) {
// Sanitize domain if passed.
if ( array_key_exists( 'domain', $data ) ) {
$data['domain'] = preg_replace( '/[^a-z0-9-.:]+/i', '', $data['domain'] );
}
// Sanitize path if passed.
if ( array_key_exists( 'path', $data ) ) {
$data['path'] = trailingslashit( '/' . trim( $data['path'], '/' ) );
}
// Sanitize network ID if passed.
if ( array_key_exists( 'network_id', $data ) ) {
$data['network_id'] = (int) $data['network_id'];
}
// Sanitize status fields if passed.
$status_fields = array( 'public', 'archived', 'mature', 'spam', 'deleted' );
foreach ( $status_fields as $status_field ) {
if ( array_key_exists( $status_field, $data ) ) {
$data[ $status_field ] = (int) $data[ $status_field ];
}
}
// Strip date fields if empty.
$date_fields = array( 'registered', 'last_updated' );
foreach ( $date_fields as $date_field ) {
if ( ! array_key_exists( $date_field, $data ) ) {
continue;
}
if ( empty( $data[ $date_field ] ) || '0000-00-00 00:00:00' === $data[ $date_field ] ) {
unset( $data[ $date_field ] );
}
}
return $data;
}
原文内容
Normalizes data for a site prior to inserting or updating in the database.
Parameters
$dataarrayrequired-
Associative array of site data passed to the respective function.
See wp_insert_site() for the possibly included data.
Source
function wp_normalize_site_data( $data ) {
// Sanitize domain if passed.
if ( array_key_exists( 'domain', $data ) ) {
$data['domain'] = preg_replace( '/[^a-z0-9-.:]+/i', '', $data['domain'] );
}
// Sanitize path if passed.
if ( array_key_exists( 'path', $data ) ) {
$data['path'] = trailingslashit( '/' . trim( $data['path'], '/' ) );
}
// Sanitize network ID if passed.
if ( array_key_exists( 'network_id', $data ) ) {
$data['network_id'] = (int) $data['network_id'];
}
// Sanitize status fields if passed.
$status_fields = array( 'public', 'archived', 'mature', 'spam', 'deleted' );
foreach ( $status_fields as $status_field ) {
if ( array_key_exists( $status_field, $data ) ) {
$data[ $status_field ] = (int) $data[ $status_field ];
}
}
// Strip date fields if empty.
$date_fields = array( 'registered', 'last_updated' );
foreach ( $date_fields as $date_field ) {
if ( ! array_key_exists( $date_field, $data ) ) {
continue;
}
if ( empty( $data[ $date_field ] ) || '0000-00-00 00:00:00' === $data[ $date_field ] ) {
unset( $data[ $date_field ] );
}
}
return $data;
}
Changelog
| Version | Description |
|---|---|
| 5.1.0 | Introduced. |