url_shorten()
Shortens the given URL.
Removes http://, www. and trims the URL to 35 characters, appending "..." at the end. You can specify up to how many characters to trim the URL.
No Hooks.
Returns
String.
Usage
url_shorten( $url, $length );
- $url(string) (required)
- URL to shorten.
- $length(integer)
- Length in characters to which the URL should be shortened.
Default: 35
Examples
#1 We'll shorten the URL, if necessary, and display it as a link.
$url = 'http://www.example.com/an/article/with/a/very/long/url'; echo '<a href="'. $url .'">'. url_shorten( $url ) .'</a>'; // get a link with a shortened anchor of the URL itself: // <a href="http://www.example.com/an/article/with/a/very/long/url">example.com/an/article/with/a/ve...</a>
#2 Demo examples
$urls = [ url_shorten( 'https://example.com/foo' ), // example.com/foo url_shorten( 'http://example.com/foo' ), // example.com/foo url_shorten( 'www.example.com/foo' ), // example.com/foo url_shorten( 'https://www.example.com/foo' ), // example.com/foo url_shorten( 'https://www.example.com/some/long/url-more-then-35-symbols' ), // example.com/some/long/url-more-t… url_shorten( '//example.com/foo' ), // //example.com/foo ]; print_r( $urls );
Changelog
| Since 1.2.0 | Introduced. |
| Since 4.4.0 | Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param. |
url_shorten() url shorten code WP 6.8.3
function url_shorten( $url, $length = 35 ) {
$stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
$short_url = untrailingslashit( $stripped );
if ( strlen( $short_url ) > $length ) {
$short_url = substr( $short_url, 0, $length - 3 ) . '…';
}
return $short_url;
}