acf_field_post_object::validate_rest_value()publicACF 1.0

Validates post object fields updated via the REST API.

Метод класса: acf_field_post_object{}

Хуков нет.

Возвращает

true|false|WP_Error.

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

$acf_field_post_object = new acf_field_post_object();
$acf_field_post_object->validate_rest_value( $valid, $value, $field );
$valid(true|false) (обязательный)
-
$value(int) (обязательный)
-
$field(массив) (обязательный)
-

Код acf_field_post_object::validate_rest_value() ACF 6.0.4

public function validate_rest_value( $valid, $value, $field ) {
	if ( is_null( $value ) ) {
		return $valid;
	}

	$param = sprintf( '%s[%s]', $field['prefix'], $field['name'] );
	$data  = array( 'param' => $param );
	$value = is_array( $value ) ? $value : array( $value );

	$invalid_posts    = array();
	$post_type_errors = array();
	$taxonomy_errors  = array();

	foreach ( $value as $post_id ) {
		if ( is_string( $post_id ) ) {
			continue;
		}

		$post_type = get_post_type( $post_id );
		if ( ! $post_type ) {
			$invalid_posts[] = $post_id;
			continue;
		}

		if (
			is_array( $field['post_type'] ) &&
			! empty( $field['post_type'] ) &&
			! in_array( $post_type, $field['post_type'] )
		) {
			$post_type_errors[] = $post_id;
		}

		if ( is_array( $field['taxonomy'] ) && ! empty( $field['taxonomy'] ) ) {
			$found = false;
			foreach ( $field['taxonomy'] as $taxonomy_term ) {
				$decoded = acf_decode_taxonomy_term( $taxonomy_term );
				if ( $decoded && is_object_in_term( $post_id, $decoded['taxonomy'], $decoded['term'] ) ) {
					$found = true;
					break;
				}
			}

			if ( ! $found ) {
				$taxonomy_errors[] = $post_id;
			}
		}
	}

	if ( count( $invalid_posts ) ) {
		$error         = sprintf(
			__( '%1$s must have a valid post ID.', 'acf' ),
			$param
		);
		$data['value'] = $invalid_posts;
		return new WP_Error( 'rest_invalid_param', $error, $data );
	}

	if ( count( $post_type_errors ) ) {
		$error         = sprintf(
			_n(
				'%1$s must be of post type %2$s.',
				'%1$s must be of one of the following post types: %2$s',
				count( $field['post_type'] ),
				'acf'
			),
			$param,
			count( $field['post_type'] ) > 1 ? implode( ', ', $field['post_type'] ) : $field['post_type'][0]
		);
		$data['value'] = $post_type_errors;

		return new WP_Error( 'rest_invalid_param', $error, $data );
	}

	if ( count( $taxonomy_errors ) ) {
		$error         = sprintf(
			_n(
				'%1$s must have term %2$s.',
				'%1$s must have one of the following terms: %2$s',
				count( $field['taxonomy'] ),
				'acf'
			),
			$param,
			count( $field['taxonomy'] ) > 1 ? implode( ', ', $field['taxonomy'] ) : $field['taxonomy'][0]
		);
		$data['value'] = $taxonomy_errors;

		return new WP_Error( 'rest_invalid_param', $error, $data );
	}

	return $valid;
}