Я хочу использовать HTML5 в своей теме WordPress, как мне отключить wptexturize?
Я не против WP добавлять разрывы, но я хочу, чтобы они были <br>
, а не <br />
. Как получить контроль над тем, как эти разрывы отображаются в моем коде?
Правка: Меня действительно волнует только проблема с тегом <br>
, я не против типографских изменений, которые она вносит.
EDIT2: На самом деле, я думаю, теги <img>
тоже имеют значение. Здесь будут иметь значение любые самозакрывающиеся автономные теги. Таким образом, <hr>
также может быть проблемой. Не говоря уже о таких элементах wp_head()
, как <link>
и различные теги <meta>
.
Разрывы строк добавляются wpautop()
, а не wptexturize()
. wpautop()
также является функцией, которая автоматически добавляет теги абзаца.
Вам лучше исправить <br />
, чем заменить фильтр. Так как wpautop()
работает с приоритетом 10, вы можете просто подключиться и исправить это.
add_filter( 'the_content', 'html5_line_breaks', 25 );
function html5_line_breaks( $content ) {
return str_replace( '<br />', '<br>', $content );
}
Редактировать после обновления OP:
Функции WordPress предназначены для вывода XHTML. Чтобы избавиться от этих косых черт в масштабе всего сайта, вам придется использовать выходной буфер. Вы можете использовать фильтр, аналогичный приведенному выше, чтобы заменить косые черты в содержимом сообщения, но это не затронет вашу голову, боковую панель и т.д.
Это немного уродливо и может оказать небольшое влияние на производительность, но здесь вы идете (поместите это в плагин или файл functions.php
вашей темы):
if ( !is_admin() && ( ! defined('DOING_AJAX') || ( defined('DOING_AJAX') && ! DOING_AJAX ) ) ) {
ob_start( 'html5_slash_fixer' );
add_action( 'shutdown', 'html5_slash_fixer_flush' );
}
function html5_slash_fixer( $buffer ) {
return str_replace( ' />', '>', $buffer );
}
function html5_slash_fixer_flush() {
ob_end_flush();
}
В этом коде написано, что если вы не находитесь в области администрирования и не выполняете обработку запроса AJAX, затем начните буферизовать вывод через фильтр, а затем с помощью ловушки завершения работы WordPress выведите этот буфер.
Ну вот:
function my_awesome_tag_fixer( $input ){
return preg_replace( '/(<.+)\s\/>/', '$1>', $input );
}
foreach( array('the_content', 'the_excerpt', 'comment_text') as $filter )
add_filter( $filter, 'my_awesome_tag_fixer', 12 );
Это не самое элегантное решение, но оно выполняется намного быстрее, чем переписывание wpautop и wptexturize.
Просто нашел это; Самозакрывающиеся теги на пустых элементах являются действительными HTML.
In HTML5 we've allowed the / on void elements (like <meta>, <img>, <br>, <input>, etc), to ease migration to and from XML.
http://lists.whatwg.org/pipermail/help-whatwg.org/2008-August/000137.html
Больше информации:
http://wiki.whatwg.org/wiki/FAQ#Should_I_close_empty_elements_with_.2F.3E_or_.3E.3F
Это можно отключить, например, function.php файла темы, используя функцию remove_filter()
(http://codex.wordpress.org/Function_Reference/remove_filter)
remove_filter("the_content", "wptexturize");
У меня есть начальная тема для html5 и WordPress, а также функция не для wptexturize, а для wpautop (). Включите также другие элементы html, такие как thead, tfoot, aside и используйте синтаксис html5, например
а также
/**
* wpautop for HTML5, allowed: table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|header|footer|hgroup|figure|details|figcaption|summary)
* @link http://nicolasgallagher.com/using-html5-elements-in-wordpress-post-content/
* @author [email protected]
*/
function html5wpautop($pee, $br = 1) {
if ( trim($pee) === '' )
return '';
$pee = $pee . "\n"; // just to make things a little easier, pad the end
$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
// Space things out a little
// *insertion* of section|article|aside|header|footer|hgroup|figure|details|figcaption|summary
$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|header|footer|hgroup|figure|details|figcaption|summary)';
$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
if ( strpos($pee, '<object') !== false ) {
$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
}
$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
// make paragraphs, including one at the end
$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
$pee = '';
foreach ( $pees as $tinkle )
$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
// *insertion* of section|article|aside
$pee = preg_replace('!<p>([^<]+)</(div|address|form|section|article|aside)>!', "<p>$1</p></$2>", $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
if ($br) {
$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
}
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
// *insertion* of img|figcaption|summary
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol|img|figcaption|summary)[^>]*>)!', '$1', $pee);
if (strpos($pee, '<pre') !== false)
$pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
return $pee;
}
// remove the original wpautop function
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wpautop');
// add our new html5autop function
add_filter('the_excerpt', 'html5wpautop');
add_filter('the_content', 'html5wpautop');
см. больше на svn темы для начинающих html5, а не на фреймворке!
Отключить WPtexturize плагин работал для меня: Отключить WPtexturize
Это довольно просто, хотя:
remove_filter('the_content', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('comment_text', 'wptexturize');