Last active
April 17, 2025 08:44
-
-
Save morgyface/b1fa82ea45a9e546dbcb9388efbc98e3 to your computer and use it in GitHub Desktop.
WordPress | Function | Simplify URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simplify a URL for display
I use this where a client is adding URLs to external sites. I use the full URL within the
hrefbut pass the same URL through this function before displaying so it's shorter and more straightforward.It basically extracts the
hostelement and then removes any traces ofwww.So, for example
http://www.website.combecomeswww.website.comafter being parsed. Thenstr_replaceswaps any instances ofwww.for nothing, so it finally returnswebsite.com.Hope it's useful. Big love from Cornwall, UK. x