WordPress 默认会使用 wpautop 将双换行符转换成段落(html 代码添加 p 标签),并且「$br 保留换行符」默认设置为 true,段落转换后剩余的任何换行符都将转换为 HTML <br />。
wpautop 例子
WordPress 官方例子:
<?php $some_long_text = 'Some long text that has many lines and paragraphs in it.'; echo wpautop( $some_long_text ); ?>
输出 html 代码如下:
<p>Some long text<br/> that has many lines</p> <p>and paragraphs in it.</p>
WordPress 仅禁止自动添加 br 换行符(保留自动添加 p)
以前就折腾过,将下面代码放入主题 functions.php 就可以禁止WordPress 自动添加 br 换行符,副作用是 p 也不会自动添加了。那时候不是刚需,就没有继续折腾。
remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' );
昨天搬运壁纸,发相册水文,又被自动 br 拦住了,找了下只禁用自动添加 br 的方法,找到一堆都是 p、br 都去掉的。
最终英文关键词找到了解决办法,其实挺简单:先去掉 p 和 br,然后在加回自动 p……将下面代码放入主题 functions.php 就可以禁止 WordPress 自动添加 br 换行符,但是会保留自动添加 p。
remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); function wpse_wpautop_nobr( $content ) { return wpautop( $content, false ); } add_filter( 'the_content', 'wpse_wpautop_nobr', 12 ); add_filter( 'the_excerpt', 'wpse_wpautop_nobr', 12 );
或者「wpautop - disable <br> tags, keep <p> tags」:
remove_filter( 'the_content', 'wpautop' ); $br = false; add_filter( 'the_content', function( $content ) use ( $br ) { return wpautop( $content, $br ); }, 12 );
温馨提示:可能需要根据实际网站 php 环境和 WordPress 版本稍稍修改。
WordPress 技巧:优先执行 Shortcode,移除 Shortcode 中自动添加的 br 和 p 标签
来源:水煮鱼
使用 WordPress Shortcode,可能会遇到个问题:WordPress 会自动在 shortcode 内添加 br 或者 p 标签,这样可能会打乱段代码原先预想的 HTML 结构和布局。
造成这个问题的原因是 WordPress 默认日志内容处理流程中,wpautop(将回车转换成 p 或者 br 标签的函数)是在 Shortcode 前面运行。解决方案也是非常简单,改变它们执行的顺序,在当前主题的 functions.php 文件中添加如下代码:
remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 12);
就可以优先执行 Shortcode!
但是这样调整顺序之后,shortcode 里面就不会有自动添加的 p 或者 br 标签,如果 shortcode 中部分内容又需要一些 p 或者 br 标签用来换行,就需要手动在自己 shortcode 处理程序中添加 wpautop 来处理:
function bio_shortcode($atts, $content = null) { $content = wpautop(trim($content)); return '<div class="bio">' . $content . '</div>'; } add_shortcode('bio', 'bio_shortcode');
另外,这样处理可能并不完美,还是需要根据实际使用情况修改。
栖息邦 收藏Ctrl+D 转载注明来源