The esc_url() WordPress PHP function is used to check and sanitize a URL. It removes specific characters from the URL, and if the URL is meant for display (which is the default behavior), it replaces ampersands as well. The ‘clean_url’ filter is applied to the URL after it’s cleaned.
Usage
To use the esc_url() function, pass the URL you want to clean as an argument. Here’s an example:
$clean_url = esc_url( $original_url );
Parameters
- $url (string) – This is the URL that needs to be cleaned.
- $protocols (array – optional) – This is an array of acceptable protocols. If none is specified, the function defaults to the return value of wp_allowed_protocols(). Default is null.
- $_context (string – optional) – This parameter is private and is used for database usage. Use sanitize_url() for this purpose. Default is ‘display’.
More information
See WordPress Developer Resources: esc_url()
This function has been implemented since WordPress 2.8.0 and is still in use as of the latest version.
Examples
Simple URL Cleaning
In this example, we are cleaning a URL before using it in an HTML anchor tag.
$original_url = "http://example.com/?s=test&foo=bar"; $clean_url = esc_url( $original_url ); echo '<a href="' . $clean_url . '">Test Link</a>';
Cleaning URL for Image Source
Here, we’re sanitizing a URL for an image source.
$image_url = "http://example.com/images/test.jpg"; $clean_url = esc_url( $image_url ); echo '<img src="' . $clean_url . '" alt="Test Image">';
Cleaning URL for Form Action
In this example, we’re sanitizing a URL for a form action attribute.
$form_submit_url = "http://example.com/form-submit"; $clean_url = esc_url( $form_submit_url ); echo '<form action="' . $clean_url . '">';
Specifying Allowed Protocols
Here, we’re extending the list of allowed protocols.
function extend_allowed_protocols( $protocols ) { $protocols[] = 'skype'; $protocols[] = 'spotify'; $protocols[] = 'macappstores'; return $protocols; } add_filter( 'kses_allowed_protocols' , 'extend_allowed_protocols' );
Cleaning Home URL for Link
In this example, we’re cleaning the home URL to use in a home link.
$home_url = home_url( '/' ); $clean_url = esc_url( $home_url ); echo '<a href="' . $clean_url . '">Home</a>';