wp_encode_emoji()
云策文档标注
概述
wp_encode_emoji() 函数用于将表情符号字符转换为等效的 HTML 实体,以便在 UTF8 字符集的数据库中存储表情符号。
关键要点
- 函数接受一个字符串参数 $content,返回编码后的字符串
- 内部调用 _wp_emoji_list('partials') 获取表情符号列表,通过 html_entity_decode() 和 preg_replace() 进行转换
- 编码后浏览器仍显示为表情符号,需查看页面源代码才能看到 HTML 实体差异
- 可使用 html_entity_decode() 将编码后的 HTML 实体转换回 Unicode 表情符号
代码示例
print_r('This is a text with emoji 🎃'); // 输出: This is a text with emoji 🎃
print_r( wp_encode_emoji('This is a text with emoji 🎃') ); // 输出: This is a text with emoji 🎃
$html_encoded = wp_encode_emoji('🎃');
$html_decoded = html_entity_decode($html_encoded);注意事项
- 函数自 WordPress 4.2.0 版本引入
- 相关函数包括 wp_staticize_emoji()、sanitize_option() 和 wp_insert_post()
- 编码主要用于数据库存储兼容性,不影响前端显示
原文内容
Converts emoji characters to their equivalent HTML entity.
Description
This allows us to store emoji in a DB using the utf8 character set.
Parameters
$contentstringrequired-
The content to encode.
Source
function wp_encode_emoji( $content ) {
$emoji = _wp_emoji_list( 'partials' );
foreach ( $emoji as $emojum ) {
$emoji_char = html_entity_decode( $emojum );
if ( str_contains( $content, $emoji_char ) ) {
$content = preg_replace( "/$emoji_char/", $emojum, $content );
}
}
return $content;
}
Changelog
| Version | Description |
|---|---|
| 4.2.0 | Introduced. |
Skip to note 2 content
Mehbub Rashid
You can also pass text with emoji.
You will not see any difference in output even after you use
wp_encode_emoji(). Because the browser will still display the html encoded version as emoji. To see the difference, you need to View page source.print_r(' This is a text with emoji 🎃' ); // This is a text with emoji 🎃 print_r( wp_encode_emoji( 'This is a text with emoji 🎃' ) ); // This is a text with emoji 🎃To convert the html encoded version back to the unicode emoji, use
html_entity_decode().$html_encoded = wp_encode_emoji( '🎃' ); $html_decoded = html_entity_decode( $html_encoded );