短代码输出添加 <br/>新线后 [英] Shortcode output adding <br /> after new line
问题描述
我正在尝试创建一个短代码来向页面添加 CSS 样式属性.我在主题的functions.php中添加了以下代码.
I'm trying to create a shortcode to add a CSS style attribute to a page. I added the following code to my theme's functions.php.
function add_style( $atts, $content = null ) {
return '<style>' . $content . '</style>';
}
add_shortcode( 'style', 'add_style' );
在页面的编辑器中我将其用作:
In the editor of the page I used it as:
[style]
.image-main{
border:5px solid lightblue;
}
[/style]
在呈现的页面上,它输出到:
On the rendered page it outputs to:
<style>
<br />
.image-main{<br />
border:5px solid lightblue;<br />
}<br />
</style>
当我有多行内容时,如何设置短代码以删除 <br/>
?
How can I set up the shortcode to remove the <br />
when I have multi-line content?
推荐答案
插入 br 标签是因为 WordPress 处理您的内容的默认顺序 - wpautop(将换行符转换为 p 或 br 标签的函数)运行在处理短代码之前.
The br tag gets inserted because of the default order in which WordPress processes your content – wpautop (the function which converts line breaks to p or br tags) is run before the shortcodes are processed.
解决方案:
更改 wpautop 的执行优先级,使其在处理完shotcodes 之后而不是之前执行.在你的functions.php文件中添加:
Change the execution priority of wpautop so that it executes after the shotcodes are processed instead of before. Add this in your functions.php file:
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);
现在将不会在您的短代码块中添加额外的 p 或 br 标签.事实上,根本不会自动将换行符转换为 p 和/或 br 标签.因此,如果您希望合法的换行符转换为 p 和 br 标签,则需要从短代码函数内部运行 wpautop,例如:
Now there will be no extra p or br tags added inside your shortcode block. In fact there will not be any automatic conversion of line breaks to p and/or br tags at all. So if you want the legitimate line breaks to convert to p and br tags, you will need to run wpautop from inside your shortcode function, e.g.:
function bio_shortcode($atts, $content = null) {
$content = wpautop(trim($content));
return '<div class="bio">' . $content . '</div>';
}
add_shortcode('bio', 'bio_shortcode');
这篇关于短代码输出添加 <br/>新线后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!