0

I've written a little shortcode, following basic instructions on Wordpress Codex:

function myshortcode( $atts, $content = null ) {
    extract( shortcode_atts( array(
        ...,
    ), $atts ) );
    return some_html _code_here . $content;
}

When I put

[myshortcode]
this 
is 
a 
test
content
[/myshortcode]

in a post, I obtain the following output:

this <br />
is <br />
a <br />
test <br />
content <br />

How can I avoid the inserting of br / tags?

  • That's normal, the text would all be on one line otherwise when displayed(which is not how you've formatted it in the editor - ie. each word is on a new line). If you don't want newlines, don't create them in the editor. – t31os Aug 10 '13 at 9:35
  • Anyway this can be a problem, as described in betterwp.net/17-protect-shortcodes-from-wpautop-and-the-likes – Toc Aug 11 '13 at 3:46
2

The <br /> tags are being added to the content by the wpautop() function. If you run your shortcode before it runs they will not be there. It is added in \wp-includes\default-filters.php with the default priority of 10.

add_filter( 'the_content', 'myshortcode', 1 );

function myshortcode( $atts, $content = null ) {
    return $content;
}

wpautop() can also add other markup besides <br /> tags.

  • I obtain a Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'myshortcode' not found or invalid function name message. – Toc Aug 9 '13 at 20:15
  • The second argument in add_filter() has to match the name of your shortcode function exactly. Copy the function name you used and paste it over the myshortcode in that line. – Charles Clarkson Aug 10 '13 at 2:23
  • I have to use do_shortcode in place of myshortcode (which is the exact name of the handler function). Thanks anyway. – Toc Aug 10 '13 at 3:54
3
function myshortcode( $atts, $content = null ) {
  return strip_tags($content,'br');
}
add_shortcode('myshortcode','myshortcode');

But I am unclear why you are you adding newlines in the first place if you don't want them.

1

You could try this one:

add_shortcode( 'myshortcode', 'myshortcode_callback' );

function myshortcode_callback( $atts, $content = null ) {
    return str_replace( '<br />', '', $content );
}   

by simply removing the <br /> tags from the output. If you want to strip all HTML tags, you can use strip_tags() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.