WordPress automatically adds break tags to new lines. Normally this is useful behaviour but it can prove a major annoyance when combined with shortcodes.
Following user requests I had added a set of column shortcodes to my Utopia theme. The shortcodes are currently just a way of adding a Bootstrap grid to the content, but as we will be replace Bootstrap with an alternative grid system in future this is a way of future proofing the content.
I found a couple of really useful tutorials for adding a columns menu to the TinyMCE visual editor in WordPress:
Bad move! Suddenly my other shortcode output was messed up. So I had to remove those lines.
The solution? Write a custom filter using regular expressions to remove line breaks between the shortcode tags and run it before the normal WordPress line break filters kick in. A regex tester proved very useful here!
$content = preg_replace(‘/(\[utopia_col_row\])([\s]*)(\[utopia_col)/i’,’$1$3′,$content);
$content = preg_replace(‘/(\[\/utopia_col_)([\_\d]+)(\])([\s]*)(\[utopia_col)/i’, ‘$1$2$3$5’, $content);
$content = preg_replace(‘/(\[\/utopia_col_)([\_\d]+)(\])([\s]*)(\[\/utopia_col_row)/i’, ‘$1$2$3$5’, $content);
add_filter( ‘the_content’, ‘utopia_cols_strip_breaks’, 0 );
I had to use three expressions as there are shortcodes for rows and columns of different widths. Whilst WordPress is supposed to handle breaks between individual shortcodes, the issue here is that we are mixing different shortcodes together and the content between them should have paragraph and line break tags added. The code above only applies to the added shortcodes and seems to work well, so problem solved!