convert_smilies()
云策文档标注
概述
convert_smilies() 函数用于将文本中的表情符号转换为图像,仅在 WordPress 设置启用且全局变量有效时执行转换。
关键要点
- 函数将文本内容中的表情符号(如 :))替换为对应的图像
- 转换条件:需启用 'use_smilies' 选项且全局变量 $wp_smiliessearch 不为空
- 函数会忽略特定 HTML 标签(如 code、pre、style、script、textarea)内的内容,避免误转换
- 返回转换后的字符串,若条件不满足则返回原文本
代码示例
// 基本用法示例
echo convert_smilies("This smiley is going to show as an image... :)");
// 在插件中通过过滤器应用
add_filter("my_plugin_content_handle", "convert_smilies");
echo apply_filters("my_plugin_content_handle", "Howdy! ;) Generated with");注意事项
- 确保 WordPress 设置中已启用表情符号功能('use_smilies' 选项为 true)
- 函数内部使用正则表达式分割文本,处理复杂 HTML 时需注意性能
- 忽略标签列表可防止在代码块或脚本中意外转换表情符号
原文内容
Converts text equivalent of smilies to images.
Description
Will only convert smilies if the option ‘use_smilies’ is true and the global used in the function isn’t empty.
Parameters
$textstringrequired-
Content to convert smilies from text.
Source
function convert_smilies( $text ) {
global $wp_smiliessearch;
if ( ! get_option( 'use_smilies' ) || empty( $wp_smiliessearch ) ) {
// Return default text.
return $text;
}
// HTML loop taken from texturize function, could possible be consolidated.
$textarr = preg_split( '/(<[^>]*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Capture the tags as well as in between.
if ( false === $textarr ) {
// Return default text.
return $text;
}
// Loop stuff.
$stop = count( $textarr );
$output = '';
// Ignore processing of specific tags.
$tags_to_ignore = 'code|pre|style|script|textarea';
$ignore_block_element = '';
for ( $i = 0; $i < $stop; $i++ ) {
$content = $textarr[ $i ];
// If we're in an ignore block, wait until we find its closing tag.
if ( '' === $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')[^>]*>/', $content, $matches ) ) {
$ignore_block_element = $matches[1];
}
// If it's not a tag and not in ignore block.
if ( '' === $ignore_block_element && strlen( $content ) > 0 && '<' !== $content[0] ) {
$content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
}
// Did we exit ignore block?
if ( '' !== $ignore_block_element && '<!--' . $ignore_block_element . '-->' === $content ) {
$ignore_block_element = '';
}
$output .= $content;
}
return $output;
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 3 content
Codex
Displays text with converted smilies
echo convert_smilies("This smiley is going to show as an image... :) ");Skip to note 4 content
Ismail
Make your plugin generated content parse emoticons:
add_filter( "my_plugin_content_handle", "convert_smilies" ); echo apply_filters( "my_plugin_content_handle", "Howdy! ;) Generated with <3 by My Custom Plugin" );