Using WordPress ‘clean_url()’ PHP function

The clean_url() WordPress PHP function checks and cleans a URL by removing a number of characters. If the URL is for displaying (the default behavior), ampersands are also replaced. The ‘clean_url’ filter is applied to the returned cleaned URL.

Usage

clean_url($url, $protocols = null, $context = 'display');

Parameters

  • $url (string): The URL to be cleaned.
  • $protocols (array, optional): An array of acceptable protocols. Default: null.
  • $context (string, optional): How the URL will be used. Default is ‘display’. Default: ‘display’.

More information

See WordPress Developer Resources: clean_url

Examples

Basic usage of clean_url()

This example demonstrates cleaning a URL for display purposes.

$url = "https://example.com?parameter=value&another_parameter=another_value";
$cleaned_url = clean_url($url);
echo $cleaned_url; // Output: "https://example.com?parameter=value&another_parameter=another_value"

Using clean_url() with a specific protocol

This example demonstrates cleaning a URL with a specific protocol.

$url = "ftp://example.com";
$protocols = array('ftp');
$cleaned_url = clean_url($url, $protocols);
echo $cleaned_url; // Output: "ftp://example.com"

Cleaning a URL for a resource

This example demonstrates cleaning a URL for a resource.

$url = "https://example.com/resource?parameter=value";
$context = 'resource';
$cleaned_url = clean_url($url, null, $context);
echo $cleaned_url; // Output: "https://example.com/resource?parameter=value"

Using clean_url() with custom protocols

This example demonstrates cleaning a URL with custom protocols.

$url = "custom://example.com";
$protocols = array('custom');
$cleaned_url = clean_url($url, $protocols);
echo $cleaned_url; // Output: "custom://example.com"

Cleaning a URL with multiple protocols

This example demonstrates cleaning a URL with multiple protocols.

$url = "https://example.com";
$protocols = array('http', 'https');
$cleaned_url = clean_url($url, $protocols);
echo $cleaned_url; // Output: "https://example.com"