The clean_url WordPress PHP filter is used to clean and escape a string for output as a URL.
Usage
add_filter('clean_url', 'your_custom_function', 10, 3); function your_custom_function($good_protocol_url, $original_url, $_context) { // your custom code here return $good_protocol_url; }
Parameters
$good_protocol_url
(string) – The cleaned URL to be returned.$original_url
(string) – The URL prior to cleaning.$_context
(string) – If ‘display’, replace ampersands and single quotes only.
More information
See WordPress Developer Resources: clean_url
Examples
Remove UTM parameters
Remove UTM parameters from URLs.
add_filter('clean_url', 'remove_utm_parameters', 10, 3); function remove_utm_parameters($good_protocol_url, $original_url, $_context) { $url_parts = parse_url($good_protocol_url); if (isset($url_parts['query'])) { parse_str($url_parts['query'], $query_params); $clean_params = array_diff_key($query_params, array_flip(['utm_source', 'utm_medium', 'utm_campaign'])); $url_parts['query'] = http_build_query($clean_params); $good_protocol_url = http_build_url($url_parts); } return $good_protocol_url; }
Add a ref parameter
Add a ‘ref’ parameter to external URLs.
add_filter('clean_url', 'add_ref_parameter', 10, 3); function add_ref_parameter($good_protocol_url, $original_url, $_context) { if (strpos($good_protocol_url, home_url()) === false) { $good_protocol_url = add_query_arg('ref', 'your_ref_value', $good_protocol_url); } return $good_protocol_url; }
Force HTTPS
Force all URLs to use HTTPS.
add_filter('clean_url', 'force_https', 10, 3); function force_https($good_protocol_url, $original_url, $_context) { return set_url_scheme($good_protocol_url, 'https'); }
Remove www
Remove ‘www’ from URLs.
add_filter('clean_url', 'remove_www', 10, 3); function remove_www($good_protocol_url, $original_url, $_context) { return preg_replace('/^www\./', '', $good_protocol_url); }
Add a trailing slash
Add a trailing slash to URLs.
add_filter('clean_url', 'add_trailing_slash', 10, 3); function add_trailing_slash($good_protocol_url, $original_url, $_context) { return trailingslashit($good_protocol_url); }