Как отключить самозакрывающиеся теги для разметки в WordPress (например, для HTML5 или HTML4)?


Я хочу использовать HTML5 в своей теме WordPress, как мне отключить wptexturize?

Я не против, чтобы WP добавлял перерывы, но я хочу, чтобы они были <br>, а не <br />. Как мне получить контроль над тем, как эти разрывы отображаются в моем коде?

РЕДАКТИРОВАТЬ: Меня действительно волнует только проблема с тегом <br>, я не возражаю против типографских изменений, которые он вносит.

EDIT2: На самом деле, я думаю, что теги <img> тоже имеют значение. Здесь будут иметь значение любые самозакрывающиеся автономные теги. Таким образом, <hr> также может быть проблемой. Не говоря уже о таких элементах wp_head(), как <link> и различные теги <meta>.

Author: artlung, 2010-08-11

6 answers

Разрывы строк добавляются с помощью 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, выведите этот буфер.

 21
Author: Viper007Bond, 2010-08-14 00:56:27

Вот, пожалуйста:

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.

 8
Author: John P Bloch, 2010-08-14 11:57:46

Только что нашел его; самозакрывающиеся теги на пустых элементах являются допустимым 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

 7
Author: Ryan Gibbons, 2010-08-13 20:18:47

Это можно отключить, например, в теме function.php файл, используя функцию remove_filter()(http://codex.wordpress.org/Function_Reference/remove_filter)

remove_filter("the_content", "wptexturize");
 6
Author: thomasjo, 2010-08-11 19:40:08

У меня есть начальная тема для html5 и WordPress, а также функция не для wptexturize, а для wpautop(). Включите также другие элементы html, такие как thead, tfoot, в сторону и используйте синтаксис 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, а не о фреймворке!

 5
Author: bueltge, 2010-08-14 06:56:41

Отключить плагин WPtexturize сработало для меня: Отключить WPtexturize

Хотя это довольно прямолинейно:

remove_filter('the_content', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
 3
Author: Bob Sherron, 2010-08-11 19:41:47