sanitize_title()WP 1.0.0

Sanitize the passed string (title) to use it as a slug (post_name). Or returns a fallback title.

By default, converts accent characters to ASCII characters and further limits the output to alphanumeric characters, underscore (_) and dash (-) through the sanitize_title filter.

If $title is empty and $fallback_title is set, the latter will be used.

1 time — 0.000197 sec (fast) | 50000 times — 6.03 sec (fast) | PHP 7.0.2, WP 4.4.2
Hooks from the function

Return

String. The sanitized string.

Usage

sanitize_title( $title, $fallback_title, $context );
$title(string) (required)
The string to be sanitized.
$fallback_title(string)
A title to use if $title is empty.
Default: ''
$context(string)
The operation for which the string is sanitized. When set to 'save', the string runs through remove_accents().
Default: 'save'

Examples

0

#1 Titles Sanitization in WordPress

Despite the name of this function, the returned value is intended to be suitable for use in a URL, not as a human-readable title.

To create the file name portion of a URL the same way that WordPress does use this:

$new_url = sanitize_title( 'This Long Title is what My Post or Page might be' );
echo $new_url; // this-long-title-is-what-my-post-or-page-might-be

One more example:

echo sanitize_title( 'sanitize_title() - HTML and PHP tags are stripped.' );

// output:
// sanitize_title-html-and-php-tags-are-stripped
Non-Latin characters

And what is happen if we pass not Latin characters:

$new_url = sanitize_title( 'Это длинный заголовок, который может быть у поста или страницы' );
echo $new_url;

// return:

// if the transliteration plugin cry2lat or similar is installed
// eto-dlinnyiy-zagolovok-kotoryiy-mozhet-byit-u-posta-ili-stranitsyi

// if cry2lat is not installed
// %d1%8d%d1%82%d0%be-%d0%b4%d0%bb%d0%b8%d0%bd%d0%bd%d1%8b%d0%b9-%d0%b7%d0%b0%d0%b3%d0%be%d0%bb%d0%be%d0%b2%d0%be%d0%ba-%d0%ba%d0%be%d1%82%d0%be%d1%80%d1%8b%d0%b9-%d0%bc%d0%be%d0%b6%d0%b5%d1%82-%d0%b1
Unicode Characters:
var_dump( sanitize_title( '𝗕𝗥𝗔𝗜𝗡𝗟𝗔𝗜𝗦𝗦' ) ); // string(0) ""

One more example for Chines characters:

$str = "這是字串";
$str = sanitize_title( $str );
echo $str; // "%e9%80%99%e6%98%af%e5%ad%97%e4%b8%b2"
0

#2 Setting the default value

echo sanitize_title( '', 'default 字串' ); //> default 字串

Changelog

Since 1.0.0 Introduced.

sanitize_title() code WP 6.5.4

function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
	$raw_title = $title;

	if ( 'save' === $context ) {
		$title = remove_accents( $title );
	}

	/**
	 * Filters a sanitized title string.
	 *
	 * @since 1.2.0
	 *
	 * @param string $title     Sanitized title.
	 * @param string $raw_title The title prior to sanitization.
	 * @param string $context   The context for which the title is being sanitized.
	 */
	$title = apply_filters( 'sanitize_title', $title, $raw_title, $context );

	if ( '' === $title || false === $title ) {
		$title = $fallback_title;
	}

	return $title;
}