繁体   English   中英

停止WordPress自动显示 <p></p> 标签

[英]Stop WordPress automatically showing <p></p> tags

WordPress会在每个地方自动生成很多不需要的<p></p>标签。 甚至img标签也被这些<p>标签包裹。 因此,它在站点中创建了多余的空白。 我尝试了多种方法来删除这些标签:-

preg_replace(array('<p>','</p>'),array('',''),the_content(),1);

remove_filter( 'the_content', 'wpautop' );

preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content)

没有什么对我有用。 首先,我想知道为什么这些标记会自动生成? 我该如何解决?

Wordpress Visual Editor本身会为新行创建这些标签。

你可以尝试删除过滤wpautopthe_excerptthe_content

remove_filter( 'the_content', 'wpautop' );
// OR
remove_filter( 'the_excerpt', 'wpautop' );

有时它不起作用(过去对我不起作用。不适用于PHP)。

您可以尝试使用Javascript / jQuery,将此代码放置在DOM加载之后或结束</body>标记之前。

jQuery('p:empty').remove();

从整个文档中删除所有空的<p></p>元素。

你可以试试这个插件

http://wordpress.org/plugins/raw-html/

否则在主题的functions.php文件中使用此用户

remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

您需要在after_setup_theme挂钩中运行remove_filter函数。 原因是它可能会在以后被内容或摘录淹没。 所以您将使用以下功能

function remove_the_wpautop_function() {
    remove_filter( 'the_content', 'wpautop' );
    remove_filter( 'the_excerpt', 'wpautop' );
}

add_action( 'after_setup_theme', 'remove_the_wpautop_function' );

WordPress中有很多插件可以禁用autop,也可以使用以下过滤器删除autop:

remove_filter( 'the_content', 'wpautop' );

但是,如果您需要对wp-editor中的内容进行样式设置和格式设置,则如果删除了autop,则将无法执行此操作。

如果要继续使用autop功能,但要删除空的p标签,则可以使用jQuery。

我可以使用以下代码删除不需要的空p标签:

jQuery(document).ready(function(){
    $ = jQuery; 
    $('p').each(function() {
    var $this = $(this);
    if($this.html().replace(/\s|&nbsp;/g, '').length == 0)
        $this.remove();
}); 

});

进入WP admin的主题编辑区域。

将此代码添加到您的functions.php文件中,并保存它。

<?php
function my_formatter($content) {
    $new_content = '';
    $pattern_full = '{(\[raw\].*?\[/raw\])}is';
    $pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
    $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

    foreach ($pieces as $piece) {
        if (preg_match($pattern_contents, $piece, $matches)) {
            $new_content .= $matches[1];
        } else {
            $new_content .= wptexturize(wpautop($piece));
        }
    }

    return $new_content;
}

remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'my_formatter', 99);
?>

现在,在撰写帖子/页面时,使用[raw] [/ raw]标签将您不想格式化的帖子/页面部分包围起来。

要么

 <?php the_content(); ?>

并将其直接放在上方:

<?php remove_filter ('the_content', 'wpautop'); ?>

它应该看起来像这样:

<?php remove_filter ('the_content', 'wpautop'); ?>

<?php the_content(); ?>
$content = preg_replace('#^<\/p>|<p>$#', '', $content);
echo do_shortcode($content);

我在短代码中使用它时尝试过,它对我有用。

我想会很好-

function my_format_TinyMCE( $in ) {
  $in['wpautop'] = false;
  return $in;
}
add_filter( 'tiny_mce_before_init', 'my_format_TinyMCE' );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM