# wp_kses_attr()

URL: https://chugunov.pro/api-wordpress/functions/wp_kses_attr/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 1.0.0.

## Сигнатура

```php
wp_kses_attr( string $element, string $attr, array[]|string $allowed_html, string[] $allowed_protocols ): string
```

## Описание

Если некоторые атрибуты разрешены, вызывает wp_kses_hair() для их дальнейшего разбора, а затем формирует новый HTML-код из данных, которые возвращает wp_kses_hair(). Также удаляет символы < и >, если они где-то остались. Кроме того, проверяет, есть ли у тега закрывающий XHTML-слэш, и если есть, добавляет его и в возвращаемый код.
Для атрибутов можно задать массив допустимых значений. Если значение атрибута не входит в этот список, атрибут удаляется из тега.
Атрибуты можно пометить как обязательные. Если обязательный атрибут отсутствует, KSES удаляет из тега все атрибуты. Поскольку KSES не сопоставляет открывающие и закрывающие теги, безопасно удалить сам тег невозможно, поэтому наиболее безопасный запасной вариант — удалить из тега все атрибуты.

## Параметры

- `$element` `string` — обязательный. HTML-элемент/тег.
- `$attr` `string` — обязательный. HTML-атрибуты от HTML-элемента до его закрывающего тега.
- `$allowed_html` `array[]|string` — обязательный. Массив допустимых HTML-элементов и атрибутов либо имя контекста, например 'post'. Список допустимых имён контекстов см. в wp_kses_allowed_html().
- `$allowed_protocols` `string[]` — обязательный. Массив разрешённых URL-протоколов.

## Возвращаемое значение

`string`

## Исходный код

Файл: `wp-includes/kses.php:1437`

```php
function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) {
	if ( ! is_array( $allowed_html ) ) {
		$allowed_html = wp_kses_allowed_html( $allowed_html );
	}

	// Is there a closing XHTML slash at the end of the attributes?
	$xhtml_slash = '';
	if ( preg_match( '%\s*/\s*$%', $attr ) ) {
		$xhtml_slash = ' /';
	}

	// Are any attributes allowed at all for this element?
	$element_low = strtolower( $element );
	if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) {
		return "<$element$xhtml_slash>";
	}

	// Split it.
	$attrarr = wp_kses_hair( $attr, $allowed_protocols );

	// Check if there are attributes that are required.
	$required_attrs = array_filter(
		$allowed_html[ $element_low ],
		static function ( $required_attr_limits ) {
			return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required'];
		}
	);

	/*
	 * If a required attribute check fails, we can return nothing for a self-closing tag,
	 * but for a non-self-closing tag the best option is to return the element with attributes,
	 * as KSES doesn't handle matching the relevant closing tag.
	 */
	$stripped_tag = '';
	if ( empty( $xhtml_slash ) ) {
		$stripped_tag = "<$element>";
	}

	// Go through $attrarr, and save the allowed attributes for this element in $attr2.
	$attr2 = '';
	foreach ( $attrarr as $arreach ) {
		// Check if this attribute is required.
		$required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] );

		if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
			$attr2 .= ' ' . $arreach['whole'];

			// If this was a required attribute, we can mark it as found.
			if ( $required ) {
				unset( $required_attrs[ strtolower( $arreach['name'] ) ] );
			}
		} elseif ( $required ) {
			// This attribute was required, but didn't pass the check. The entire tag is not allowed.
			return $stripped_tag;
		}
	}

	// If some required attributes weren't set, the entire tag is not allowed.
	if ( ! empty( $required_attrs ) ) {
		return $stripped_tag;
	}

	// Remove any "<" or ">" characters.
	$attr2 = preg_replace( '/[<>]/', '', $attr2 );

	return "<$element$attr2$xhtml_slash>";
}
```

## История изменений

- 5.9.0 — Added support for an array of allowed values for attributes. Added support for required attributes.
- 1.0.0 — Introduced.

## Связанные

Использует: [`wp_kses_attr_check`](https://chugunov.pro/api-wordpress/functions/wp_kses_attr_check/), [`wp_kses_hair`](https://chugunov.pro/api-wordpress/functions/wp_kses_hair/), [`wp_kses_allowed_html`](https://chugunov.pro/api-wordpress/functions/wp_kses_allowed_html/).

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/wp_kses_attr/
