sanitize_title()
Cleans the given string (title) for use as a slug.
HTML and PHP tags will be removed from the title. If $title turns out to be empty, the value from $fallback_title will be used instead.
Despite the function's name, it can be used in URLs to get rid of spaces and other unwanted characters.
Hooks from the function
Returns
String.
Usage
sanitize_title( $title, $fallback_title, $context );
- $title(string) (required)
- The string to be cleaned.
- $fallback_title(string)
- The title that will be used if $title is not provided.
Default: '' - $context(string)
The context in which to clean the name passed in $title. The value is passed to the filter
'sanitize_title'.When
'save'(default), the string goes through the remove_accents() function.
Default: 'save'
Examples
#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"
#2 Setting the default value
echo sanitize_title( '', 'default 字串' ); //> default 字串
Changelog
| Since 1.0.0 | Introduced. |