Описание
Функция форматирования текста. В её задачи входит изменить текст на более правильный, читаемый и визуально привлекательный.
Текст изменяется следующим образом:
"текст в кавычках" станет “текстом в лапках”
'текст в кавычках' станет ‘текстом в лапках’
--- станет —
-- станет –
... станет …
(c) станет ©
(r) станет ®
(tm) станет ™
'' станет ”
`` станет “
president's станет president’s
presidents' станет presidents’
12' станет 12′
12" станет 12″
2x4 станет 2×4
Ниже список фильтров к которым, по умолчанию, применяется функция wptexturize():
- comment_author
- term_name
- link_name
- link_description
- link_notes
- bloginfo
- wp_title
- widget_title
- single_post_title
- single_cat_title
- single_tag_title
- single_month_title
- nav_menu_attr_title
- nav_menu_description
- term_description
- list_cats
- widget_text
В версиях ниже 3.0 (точно не могу сказать в каких) эта функция была фильтром текста и для функций:
- the_content()
- the_excerpt()
- the_title()
- comment_text()
Использование этой функции недопустимо для программного кода, потому что в нем могут быть изменены символы.
Если нужно указать html теги или шоткоды исключения, т.е. такие, где функция работать не будет, то используйте фильтры no_texturize_tags и no_texturize_shortcodes соответственно.
wptexturize() возвращает отформатированный текст.
Использование
<?php $new_text = wptexturize($text); ?>
wptexturize()
из файла: /wp-includes/formatting.php WP 3.3.2function wptexturize($text) {
global $wp_cockneyreplace;
static $opening_quote, $closing_quote, $en_dash, $em_dash, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
// No need to set up these static variables more than once
if ( empty( $opening_quote ) ) {
/* translators: opening curly quote */
$opening_quote = _x('“', 'opening curly quote');
/* translators: closing curly quote */
$closing_quote = _x('”', 'closing curly quote');
/* translators: en dash */
$en_dash = _x('–', 'en dash');
/* translators: em dash */
$em_dash = _x('—', 'em dash');
$default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
$default_no_texturize_shortcodes = array('code');
// if a plugin has provided an autocorrect array, use it
if ( isset($wp_cockneyreplace) ) {
$cockney = array_keys($wp_cockneyreplace);
$cockneyreplace = array_values($wp_cockneyreplace);
} else {
$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
}
$static_characters = array_merge( array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)'), $cockney );
$static_replacements = array_merge( array($em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™'), $cockneyreplace );
$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/\'(\d)/', '/(\s|\A|[([{<]|")\'/', '/(\d)"/', '/(\d)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
$dynamic_replacements = array('’$1','’$1', '$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');
}
// Transform into regexp sub-expression used in _wptexturize_pushpop_element
// Must do this everytime in case plugins use these filters in a context sensitive manner
$no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
$no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
$no_texturize_tags_stack = array();
$no_texturize_shortcodes_stack = array();
$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ( $textarr as &$curl ) {
if ( empty( $curl ) )
continue;
// Only call _wptexturize_pushpop_element if first char is correct tag opening
$first = $curl[0];
if ( '<' === $first ) {
_wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
} elseif ( '[' === $first ) {
_wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
} elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
// This is not a tag, nor is the texturization disabled static strings
$curl = str_replace($static_characters, $static_replacements, $curl);
// regular expressions
$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
}
$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
}
return implode( '', $textarr );
}Ещё из раздела
Смотрите также: Функции WordPress и Теги Шаблона.
Драгоценности в кольцах всегда будут оценены выше и будут смотреться богаче, чем кольцо само по себе. К примеру, перстень с изумрудом придаст кольцу небывалый шарм и добавит ту изюминку, которой так часто не хватает в перстнях.
Одного раздела недостаёт: как от этой замечательной функции избавляться, чтобы не уничтожала осмысленно введенный код.
Это насколько же надо быть извращенцем, чтобы насильственно встроить бездарно типографирующую всё и вся функцию в такое место, куда приходится добираться автогеном через кольцевидную мышцу! И это индийское решение разработчики WP неизменно тянут из версии в версию уже лет пять…
Судя по комментарию у вас с этой функций что-то личное
Избавится от нее можно вставив в functions.php вашей темы такой код:
remove_filter('the_content', 'wptexturize');Вместо the_content укажите фильтр где вам нужно, чтобы она не работала. В статье фильтры указаны.
У меня личное?! Вот строго у одного меня?
Why are WordPress developers so DUMB? It’s something I’ve seen in other projects: the bigger the project the more disconnected from the real world the developers are. Why do they insist in adding the fucking auto formatting to WordPress posts? And if thy think there is a reason in doing so, why the hell don’t they include a fucking option to disable it. A fucking option to disable the shitty TinyMCE editor and the auto formatting all together? A tag to tell that stupid editor “don’t fucking touch this code bitch”?
http://antonio.rojilla.com/2010/07/19/wordpress-auto-formatting-sucks-wp-developers-are-dumb/
I don't know why developers of such a great blogging platform are not realizing the cons of so called "auto formatting". Iam sorry if I sound bad but why the hell wordpress auto formats my html i put into the text editor. I do not see any logic behind this.
Its like; I buy dreamweaver and make webpage but upon saving it "autoformat".
http://wordpress.org/extend/ideas/topic/modify-annoying-html-autoformat-before-releasing-28
B так далее, и тому подобное.
---
П.С. комментарий отредактирован автором блога
Я больше шутил, чем всерьез насчет "личного" и уж точно не хотел вас обидеть! Просто, ваш комментарий получился эмоциональный, вот я и предположил, что эта функция заставила вас помучится...
Вообще, разработчики убрали её действия в форматирования контента (the_content) с версии 3.0+
Да вы что, я и не думал обижаться! Меня вообще обидеть сложновато, скорее уж наоборот (http://ru.forums.wordpress.org/topic/%d0%98%d0%b7%d0%b1%d0%b0%d0%b2%d0%b8%d1%82%d1%8c%d1%81%d1%8f-%d0%be%d1%82-%d0%bf%d1%80%d0%b5%d0%be%d0%b1%d1%80%d0%b0%d0%b7%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f-%d1%87%d0%b8%d1%81%d0%bb%d0%be%d0%b2%d1%8b%d1%85-%d1%8d%d0%ba%d0%b2%d0%b8%d0%b2%d0%b0%d0%bb?replies=12#post-54086).
Мучиться не пришлось — мне сразу подсказали умные слова для поиска (так я и ваш блог обнаружил), но вот насчёт «убрали» вас, похоже, надули: в 3.0.4 (других не проверял) фсьо кака бычна.