sanitize_post() WordPress Function

The sanitize_post() function in WordPress is used to clean up data passed through the $_POST array. This function strips away any unwanted characters, such as backslashes, from the data before it is stored in the database.

sanitize_post( object|WP_Post|array $post, string $context = 'display' ) #

Sanitizes every post field.


Description

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

Top ↑

See also


Top ↑

Parameters

$post

(object|WP_Post|array)(Required)The post object or array

$context

(string)(Optional) How to sanitize post fields. Accepts 'raw', 'edit', 'db', 'display', 'attribute', or 'js'.

Default value: 'display'


Top ↑

Return

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


Top ↑

Source

File: wp-includes/post.php

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;
}


Top ↑

Changelog

Changelog
VersionDescription
2.3.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More