WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/sanitize post field

Description

Sanitize a post field based on the context of where the field is being used.

Usage

<?php sanitize_post_field$field$value$post_id$context ); ?>

Parameters

$field
(string) (required) The post object field name
Default: None
$value
(mixed) (required) The post object value
Default: None
$post_id
(integer) (required) The Post ID
Default: None
$context
(string) (optional) How to sanitize post fields. Can be: 'raw', 'edit', 'db', 'display', 'attribute' or 'js'
Default: display

Return Values

mixed 
The sanitized value

Examples

Sanitizing for Display

Sanitize a post title for display:

$post = get_post( 35 );

$post_title = sanitize_post_field( 'post_title', $post->post_title, $post->ID, 'display' );

echo $post_title;

Sanitizing for Attributes

Sanitize a post title for use as the value of a hidden form field:

$post = get_post( 543 );

$post_title = sanitize_post_field( 'post_title', $post->post_title, $post->ID, 'attribute' );

echo '<input type="hidden" name="post-title" value="' . $post_title . '" />';

Notes

  • Uses apply_filters():
    • Calls 'edit_{$field}' and '{$field_no_prefix}_edit_pre' passing $value and $post_id if $context is 'edit' and field name prefix is 'post_'.
    • Calls 'edit_post_{$field}' passing $value and $post_id if $context is 'db'.
    • Calls 'pre_{$field}' passing $value if $context is 'db' and field name prefix is 'post_'.
    • Calls '{$field}_pre' passing $value if $context is 'db' and field name prefix is not 'post_'.
    • Calls '{$field}' passing $value, $post_id and $context if $context is anything other than 'raw', 'edit' and 'db' and field name prefix is 'post_'.
    • Calls 'post_$field' passing $value if $context is anything other than 'raw', 'edit' and 'db' and field name prefix is not 'post_'.

Change Log

Since: 2.3.0

Source File

sanitize_post_field() is located in wp-includes/post.php.

Related

sanitize_post_field() is in a class of functions that help you sanitize potentially unsafe data which allow you to pass an arbitrary variable and receive the clean version based on data type. Others include:

This page is marked as incomplete. You can help Codex by expanding it.