Friday, July 15, 2016

WordPress shortcodes and line breaks.

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:

All well and good, but when I published the content WordPress added break tags between the div
tags and the columns did not display.

My first solution was to change the order of WordPress' shortcode_unautop and wpautop filters, as per these instructions.


//move wpautop filter to AFTER shortcode is processed
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 99);
add_filter( 'the_content', 'shortcode_unautop',100 );

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!

function utopia_cols_strip_breaks( $content ) {
$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);
    return $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!

No comments:

Popular Posts