sanitize_post_field()WP 2.3.0

Очищает указанное значение указанного поля поста. Уровень очистки указывается в параметре $context.

Основа для: sanitize_post(), get_post_field()

Возвращает

Разное. Очищенное значение.

Использование

sanitize_post_field( $field, $value, $post_id, $context );
$field(строка) (обязательный)

Название поля объекта поста. Возможные значения:

ID
post_author
post_date
post_date_gmt
post_content
post_title
post_excerpt
post_status
comment_status
ping_status
post_password
post_name
to_ping
pinged
post_modified
post_modified_gmt
post_content_filtered
post_parent
guid
menu_order
post_type
post_mime_type
comment_count
filter
$value(смешанный) (обязательный)
Значение поля объекта поста.
$post_id(число) (обязательный)
ID поста.
$context(строка) (обязательный)

Как проводить очистку указанного поля. Может быть:

  • raw - для использования в строке;
  • edit - для дальнейшего редактирования;
  • db - для использования в запросе;
  • display - для вывода на экран;
  • attribute - для использования в атрибуте;
  • js - для использования в данных скрипта.

По умолчанию: 'display'

Примеры

0

#1 Очистка для вывода на экран

Очистим заголовок поста перед выводом его на экран:

$post = get_post( 35 );

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

echo $post_title;
0

#2 Очистка для атрибутов

Почистим значение поля перед использованием его в атрибуте HTML тега. Удалит теги и прочее, чтобы значение можно было использовать в атрибуте и оно не вызвало ошибок:

$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 . '" />';

Список изменений

С версии 2.3.0 Введена.
С версии 4.4.0 Like sanitize_post(), $context defaults to 'display'.

Код sanitize_post_field() WP 6.5.2

function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
	$int_fields = array( 'ID', 'post_parent', 'menu_order' );
	if ( in_array( $field, $int_fields, true ) ) {
		$value = (int) $value;
	}

	// Fields which contain arrays of integers.
	$array_int_fields = array( 'ancestors' );
	if ( in_array( $field, $array_int_fields, true ) ) {
		$value = array_map( 'absint', $value );
		return $value;
	}

	if ( 'raw' === $context ) {
		return $value;
	}

	$prefixed = false;
	if ( str_contains( $field, 'post_' ) ) {
		$prefixed        = true;
		$field_no_prefix = str_replace( 'post_', '', $field );
	}

	if ( 'edit' === $context ) {
		$format_to_edit = array( 'post_content', 'post_excerpt', 'post_title', 'post_password' );

		if ( $prefixed ) {

			/**
			 * Filters the value of a specific post field to edit.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the post
			 * field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed $value   Value of the post field.
			 * @param int   $post_id Post ID.
			 */
			$value = apply_filters( "edit_{$field}", $value, $post_id );

			/**
			 * Filters the value of a specific post field to edit.
			 *
			 * The dynamic portion of the hook name, `$field_no_prefix`, refers to
			 * the post field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed $value   Value of the post field.
			 * @param int   $post_id Post ID.
			 */
			$value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
		} else {
			$value = apply_filters( "edit_post_{$field}", $value, $post_id );
		}

		if ( in_array( $field, $format_to_edit, true ) ) {
			if ( 'post_content' === $field ) {
				$value = format_to_edit( $value, user_can_richedit() );
			} else {
				$value = format_to_edit( $value );
			}
		} else {
			$value = esc_attr( $value );
		}
	} elseif ( 'db' === $context ) {
		if ( $prefixed ) {

			/**
			 * Filters the value of a specific post field before saving.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the post
			 * field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed $value Value of the post field.
			 */
			$value = apply_filters( "pre_{$field}", $value );

			/**
			 * Filters the value of a specific field before saving.
			 *
			 * The dynamic portion of the hook name, `$field_no_prefix`, refers
			 * to the post field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed $value Value of the post field.
			 */
			$value = apply_filters( "{$field_no_prefix}_save_pre", $value );
		} else {
			$value = apply_filters( "pre_post_{$field}", $value );

			/**
			 * Filters the value of a specific post field before saving.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the post
			 * field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed $value Value of the post field.
			 */
			$value = apply_filters( "{$field}_pre", $value );
		}
	} else {

		// Use display filters by default.
		if ( $prefixed ) {

			/**
			 * Filters the value of a specific post field for display.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the post
			 * field name.
			 *
			 * @since 2.3.0
			 *
			 * @param mixed  $value   Value of the prefixed post field.
			 * @param int    $post_id Post ID.
			 * @param string $context Context for how to sanitize the field.
			 *                        Accepts 'raw', 'edit', 'db', 'display',
			 *                        'attribute', or 'js'. Default 'display'.
			 */
			$value = apply_filters( "{$field}", $value, $post_id, $context );
		} else {
			$value = apply_filters( "post_{$field}", $value, $post_id, $context );
		}

		if ( 'attribute' === $context ) {
			$value = esc_attr( $value );
		} elseif ( 'js' === $context ) {
			$value = esc_js( $value );
		}
	}

	// Restore the type for integer fields after esc_attr().
	if ( in_array( $field, $int_fields, true ) ) {
		$value = (int) $value;
	}

	return $value;
}