Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active April 17, 2025 08:44
Show Gist options
  • Select an option

  • Save morgyface/b1fa82ea45a9e546dbcb9388efbc98e3 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/b1fa82ea45a9e546dbcb9388efbc98e3 to your computer and use it in GitHub Desktop.
WordPress | Function | Simplify URL
<?php
// Simplify the URL for display purposes. Remove http(s) the www and any queries.
function url_simplify( $url ) {
if ( $url ) {
$url_parse = wp_parse_url( $url );
if( $url_parse ) {
$url_host = $url_parse['host'];
$url_host = str_replace( 'www.','',$url_host );
$url_simple = $url_host;
if( array_key_exists('path', $url_parse) ) {
$url_path = $url_parse['path'];
if ( $url_path != '/' ) {
$url_simple = $url_host . $url_path;
}
}
return $url_simple;
} else {
return $url;
}
}
return null;
}
?>
@morgyface
Copy link
Author

morgyface commented Apr 9, 2018

Simplify a URL for display

I use this where a client is adding URLs to external sites. I use the full URL within the href but pass the same URL through this function before displaying so it's shorter and more straightforward.

It basically extracts the host element and then removes any traces of www.

So, for example http://www.website.com becomes www.website.com after being parsed. Then str_replace swaps any instances of www. for nothing, so it finally returns website.com.

Hope it's useful. Big love from Cornwall, UK. x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment