url_shorten()WP 1.2.0

Shorten a URL, to be used as link text.

No Hooks.

Return

String. Shortened URL.

Usage

url_shorten( $url, $length );
$url(string) (required)
URL to shorten.
$length(int)
Maximum length of the shortened URL.
Default: 35 characters

Examples

0

#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>
0

#2 Handle 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() code WP 6.4.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 ) . '&hellip;';
	}
	return $short_url;
}