Responsive Columns Shortcode
Adds [layout_columns] and [layout_col] shortcodes that place content side by side in two, three or four columns and stack them on phones, for classic editor content and page builders without a columns tool.
Opens WPIDE on
Code
add_action( 'init', function () {
wp_register_style( 'wpide-columns', false, array(), '1.0' );
wp_add_inline_style( 'wpide-columns', '.wpide-cols{display:flex;flex-wrap:wrap;gap:var(--wpide-gap,1.5rem);margin:1.5em 0}.wpide-col{flex:1 1 0;min-width:0}.wpide-col>:first-child{margin-top:0}.wpide-col>:last-child{margin-bottom:0}@media (max-width:640px){.wpide-col{flex-basis:100%!important}}' );
add_shortcode( 'layout_columns', function ( $atts, $content = '' ) {
$atts = shortcode_atts( array( 'gap' => '1.5rem', 'class' => '' ), $atts, 'layout_columns' );
wp_enqueue_style( 'wpide-columns' );
// Remove the stray paragraphs wpautop adds between [layout_col] tags.
$content = preg_replace( '#^\s*</p>|<p>\s*$#', '', trim( $content ) );
return sprintf(
'<div class="wpide-cols %s" style="--wpide-gap:%s">%s</div>',
esc_attr( $atts['class'] ),
esc_attr( preg_replace( '/[^0-9a-z.%]/i', '', $atts['gap'] ) ),
do_shortcode( shortcode_unautop( $content ) )
);
} );
add_shortcode( 'layout_col', function ( $atts, $content = '' ) {
$atts = shortcode_atts( array( 'width' => '' ), $atts, 'layout_col' );
$width = preg_replace( '/[^0-9.%a-z]/i', '', $atts['width'] );
return sprintf(
'<div class="wpide-col"%s>%s</div>',
$width ? ' style="flex:0 0 calc(' . esc_attr( $width ) . ' - var(--wpide-gap,1.5rem))"' : '',
wpautop( do_shortcode( trim( $content ) ) )
);
} );
} );
Notes
Example [layout_columns gap="2rem"][layout_col]Left[/layout_col][layout_col]Right[/layout_col][/layout_columns]; columns share the width equally unless you add width="30%".
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.