url_shorten() WordPress Function

If you've ever wanted to create a shortened URL, this function is for you. Just enter the URL you want to shorten, and the function will do the rest.

url_shorten( string $url, int $length = 35 ) #

Shortens a URL, to be used as link text.


Parameters

$url

(string)(Required)URL to shorten.

$length

(int)(Optional) Maximum length of the shortened URL. Default 35 characters.

Default value: 35


Top ↑

Return

(string) Shortened URL.


Top ↑

Source

File: wp-includes/formatting.php

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;
}


Top ↑

Changelog

Changelog
VersionDescription
4.4.0Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param.
1.2.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More