函数文档

sanitize_post()

💡 云策文档标注

概述

sanitize_post() 函数用于对文章对象或数组的所有字段进行清理,基于指定的上下文参数。它通过调用 sanitize_post_field() 来确保数据安全,并避免重复处理。

关键要点

  • 函数接受 $post 参数(可以是对象或数组)和可选的 $context 参数(如 'raw'、'edit'、'display' 等),默认值为 'display'。
  • 如果 $post 已通过相同上下文过滤(通过 filter 属性或键检查),则直接返回,避免重复清理。
  • 对于对象或数组类型,函数遍历所有字段,使用 sanitize_post_field() 进行清理,并设置 filter 属性以标记上下文。
  • 返回类型与输入 $post 相同(对象或数组),确保数据一致性。

代码示例

function sanitize_post( $post, $context = 'display' ) {
	if ( is_object( $post ) ) {
		// Check if post already filtered for this context.
		if ( isset( $post->filter ) && $context === $post->filter ) {
			return $post;
		}
		if ( ! isset( $post->ID ) ) {
			$post->ID = 0;
		}
		foreach ( array_keys( get_object_vars( $post ) ) as $field ) {
			$post->$field = sanitize_post_field( $field, $post->$field, $post->ID, $context );
		}
		$post->filter = $context;
	} elseif ( is_array( $post ) ) {
		// Check if post already filtered for this context.
		if ( isset( $post['filter'] ) && $context === $post['filter'] ) {
			return $post;
		}
		if ( ! isset( $post['ID'] ) ) {
			$post['ID'] = 0;
		}
		foreach ( array_keys( $post ) as $field ) {
			$post[ $field ] = sanitize_post_field( $field, $post[ $field ], $post['ID'], $context );
		}
		$post['filter'] = $context;
	}
	return $post;
}

注意事项

  • 当上下文为 'raw' 时,仅对整数字段进行最小清理,适用于需要原始数据的场景。
  • 函数自 WordPress 2.3.0 版本引入,是核心清理机制的一部分,常用于文章数据处理。
  • 相关函数如 sanitize_post_field() 提供了更细粒度的字段清理,可结合使用。

📄 原文内容

Sanitizes every post field.

Description

If the context is ‘raw’, then the post object or array will get minimal sanitization of the integer fields.

See also

Parameters

$postobject|WP_Post|arrayrequired
The post object or array
$contextstringoptional
How to sanitize post fields.
Accepts 'raw', 'edit', 'db', 'display', 'attribute', or 'js'. Default 'display'.

Return

object|WP_Post|array The now sanitized post object or array (will be the same type as $post).

Source

function sanitize_post( $post, $context = 'display' ) {
	if ( is_object( $post ) ) {
		// Check if post already filtered for this context.
		if ( isset( $post->filter ) && $context === $post->filter ) {
			return $post;
		}
		if ( ! isset( $post->ID ) ) {
			$post->ID = 0;
		}
		foreach ( array_keys( get_object_vars( $post ) ) as $field ) {
			$post->$field = sanitize_post_field( $field, $post->$field, $post->ID, $context );
		}
		$post->filter = $context;
	} elseif ( is_array( $post ) ) {
		// Check if post already filtered for this context.
		if ( isset( $post['filter'] ) && $context === $post['filter'] ) {
			return $post;
		}
		if ( ! isset( $post['ID'] ) ) {
			$post['ID'] = 0;
		}
		foreach ( array_keys( $post ) as $field ) {
			$post[ $field ] = sanitize_post_field( $field, $post[ $field ], $post['ID'], $context );
		}
		$post['filter'] = $context;
	}
	return $post;
}

Changelog

Version Description
2.3.0 Introduced.