Shortcode output adding <br /> after new line

人盡茶涼 提交于 2019-12-05 01:13:19

问题


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>

How can I set up the shortcode to remove the <br /> when I have multi-line content?


回答1:


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.

The Solution:

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);

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');



回答2:


The solution I found to my problem was to replace remove "<br /r>" using str_replace();

function add_style( $atts, $content = null ) {
    $pure_content = str_replace("<br />","",$content);
    return '<style>' . $pure_content . '</style>';
}
add_shortcode( 'style', 'add_style' );


来源:https://stackoverflow.com/questions/32570351/shortcode-output-adding-br-after-new-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!