# esc_url()

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

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

## Сигнатура

```php
esc_url( string $url, string[] $protocols = null, string $_context = 'display' ): string
```

## Описание

Из URL удаляется ряд символов. Если URL предназначен для отображения (поведение по умолчанию), также заменяются амперсанды. К возвращаемому очищенному URL применяется фильтр ‘clean_url’.

## Параметры

- `$url` `string` — обязательный. URL, который нужно очистить.
- `$protocols` `string[]` — необязательный, по умолчанию `null`. Массив допустимых протоколов.
  
  По умолчанию — возвращаемое значение wp_allowed_protocols() .
- `$_context` `string` — необязательный, по умолчанию `'display'`. Приватный. Используйте sanitize_url() для работы с базой данных.

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

`string` — 'clean_url' $url $protocols $url

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

Файл: `wp-includes/formatting.php:4480`

```php
function esc_url( $url, $protocols = null, $_context = 'display' ) {
	$original_url = $url;

	if ( '' === $url ) {
		return $url;
	}

	$url = str_replace( ' ', '%20', ltrim( $url ) );
	$url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );

	if ( '' === $url ) {
		return $url;
	}

	if ( 0 !== stripos( $url, 'mailto:' ) ) {
		$strip = array( '%0d', '%0a', '%0D', '%0A' );
		$url   = _deep_replace( $strip, $url );
	}

	$url = str_replace( ';//', '://', $url );
	/*
	 * If the URL doesn't appear to contain a scheme, we presume
	 * it needs http:// prepended (unless it's a relative link
	 * starting with /, # or ?, or a PHP file). If the first item
	 * in $protocols is 'https', then https:// is prepended.
	 */
	if ( ! str_contains( $url, ':' ) && ! in_array( $url[0], array( '/', '#', '?' ), true ) &&
		! preg_match( '/^[a-z0-9-]+?\.php/i', $url )
	) {
		$scheme = ( is_array( $protocols ) && 'https' === array_first( $protocols ) ) ? 'https://' : 'http://';
		$url    = $scheme . $url;
	}

	// Replace ampersands and single quotes only when displaying.
	if ( 'display' === $_context ) {
		$url = wp_kses_normalize_entities( $url );
		$url = str_replace( '&amp;', '&#038;', $url );
		$url = str_replace( "'", '&#039;', $url );
	}

	if ( str_contains( $url, '[' ) || str_contains( $url, ']' ) ) {

		$parsed = wp_parse_url( $url );
		$front  = '';

		if ( isset( $parsed['scheme'] ) ) {
			$front .= $parsed['scheme'] . '://';
		} elseif ( '/' === $url[0] ) {
			$front .= '//';
		}

		if ( isset( $parsed['user'] ) ) {
			$front .= $parsed['user'];
		}

		if ( isset( $parsed['pass'] ) ) {
			$front .= ':' . $parsed['pass'];
		}

		if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
			$front .= '@';
		}

		if ( isset( $parsed['host'] ) ) {
			$front .= $parsed['host'];
		}

		if ( isset( $parsed['port'] ) ) {
			$front .= ':' . $parsed['port'];
		}

		$end_dirty = str_replace( $front, '', $url );
		$end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
		$url       = str_replace( $end_dirty, $end_clean, $url );

	}

	if ( '/' === $url[0] ) {
		$good_protocol_url = $url;
	} else {
		if ( ! is_array( $protocols ) ) {
			$protocols = wp_allowed_protocols();
		}
		$good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
		if ( strtolower( $good_protocol_url ) !== strtolower( $url ) ) {
			return '';
		}
	}

	/**
	 * Filters a string cleaned and escaped for output as a URL.
	 *
	 * @since 2.3.0
	 *
	 * @param string $good_protocol_url The cleaned URL to be returned.
	 * @param string $original_url      The URL prior to cleaning.
	 * @param string $_context          If 'display', replace ampersands and single quotes only.
	 */
	return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
}
```

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

- 6.9.0 — Prepends https:// to the URL if it does not already contain a scheme and the first item in $protocols is 'https'.
- 2.8.0 — Introduced.

## Связанные

Использует: [`stripos`](https://chugunov.pro/api-wordpress/functions/stripos/), [`wp_parse_url`](https://chugunov.pro/api-wordpress/functions/wp_parse_url/), [`_deep_replace`](https://chugunov.pro/api-wordpress/functions/_deep_replace/), [`wp_kses_normalize_entities`](https://chugunov.pro/api-wordpress/functions/wp_kses_normalize_entities/), [`wp_kses_bad_protocol`](https://chugunov.pro/api-wordpress/functions/wp_kses_bad_protocol/), [`wp_allowed_protocols`](https://chugunov.pro/api-wordpress/functions/wp_allowed_protocols/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/).
Используется в: [`wp_options_connectors_render_page`](https://chugunov.pro/api-wordpress/functions/wp_options_connectors_render_page/), [`wp_font_library_render_page`](https://chugunov.pro/api-wordpress/functions/wp_font_library_render_page/), [`_block_template_add_skip_link`](https://chugunov.pro/api-wordpress/functions/_block_template_add_skip_link/), `WP_Site_Health::get_test_opcode_cache`, `WP_Site_Health::get_test_insecure_registration`, `WP_Site_Health::get_test_search_engine_visibility`, [`_block_bindings_post_data_get_value`](https://chugunov.pro/api-wordpress/functions/_block_bindings_post_data_get_value/), [`_block_bindings_term_data_get_value`](https://chugunov.pro/api-wordpress/functions/_block_bindings_term_data_get_value/), `WP_Site_Health::get_test_autoloaded_options`, `WP_Plugin_Dependencies::display_admin_notice_for_unmet_dependencies`, `WP_Script_Modules::print_script_module_preloads`, `WP_Plugin_Install_List_Table::get_more_details_link`, [`wp_get_plugin_action_button`](https://chugunov.pro/api-wordpress/functions/wp_get_plugin_action_button/), `WP_Plugins_List_Table::get_view_details_link`, `Walker_Nav_Menu::build_atts`, `WP_HTML_Tag_Processor::set_attribute`, [`wp_preload_resources`](https://chugunov.pro/api-wordpress/functions/wp_preload_resources/), `WP_Site_Health::get_test_persistent_object_cache`, `WP_List_Table::get_views_links`, `WP_Widget_Media::get_l10n_defaults`, [`wp_list_users`](https://chugunov.pro/api-wordpress/functions/wp_list_users/), [`deactivated_plugins_notice`](https://chugunov.pro/api-wordpress/functions/deactivated_plugins_notice/), [`wp_is_local_html_output`](https://chugunov.pro/api-wordpress/functions/wp_is_local_html_output/), `WP_Site_Health::get_test_authorization_header`, `WP_Sitemaps::add_robots`, `WP_Sitemaps_Renderer::get_sitemap_index_xml`, `WP_Sitemaps_Renderer::get_sitemap_xml`, `WP_Sitemaps_Renderer::__construct`, `WP_Sitemaps_Renderer`, `WP_Sitemaps_Stylesheet::get_sitemap_stylesheet`, `WP_Sitemaps_Stylesheet::get_sitemap_index_stylesheet`, `WP_Automatic_Updater::send_plugin_theme_email`, [`wp_dashboard_site_health`](https://chugunov.pro/api-wordpress/functions/wp_dashboard_site_health/), [`wp_credits_section_list`](https://chugunov.pro/api-wordpress/functions/wp_credits_section_list/), `WP_Privacy_Data_Removal_Requests_List_Table::column_email`, `WP_Privacy_Data_Removal_Requests_List_Table::column_next_steps`, `WP_MS_Sites_List_Table::get_views`, `WP_Privacy_Data_Export_Requests_List_Table::column_email`, `WP_Privacy_Data_Export_Requests_List_Table::column_next_steps`, [`wp_get_update_php_annotation`](https://chugunov.pro/api-wordpress/functions/wp_get_update_php_annotation/).

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