In order to keep text to a nice readable width on desktops (yes, there is such a thing as an optimal line length!) it’s often useful to split it into two columns. Here’s a little function for WordPress which will take your standard content and pop it in two columns.
/* ** Columnize the post content */ function content_columnsd($content){ $cumulative=0; for ($i=0; $i < substr_count($content, '<p'); $i++) { $offset = 0; $length = strpos($content,'</p>')+4; if($i!=0){ $offset = strpos($content, '<p',$cumulative); $length = strpos($content, '</p>',$offset) + 4 - $cumulative; } $slices[$i] = substr($content, $offset, $length); $cumulative = $cumulative + strlen($slices[$i]); } if(isset($slices) && is_array($slices)) { $breakpoint = ceil(count($slices)/2); if($breakpoint >= 1) { $b=0; $output = '<div class="columns first">'; foreach($slices as $key => $s) { if($b==$breakpoint && $breakpoint >= 1) { $output .= '</div><div class="columns last">'; } $output .= $s; $b++; } $output.= '</div>'; $content = $output; } } return $content; } add_filter('the_content','content_columnsd',999);
So we’re taking the $content right at the end, so shortcodes and paragraphs etc have been added, then it’s looping through occurrences of “<p” – no closing bracket in case the user aligns the paragraphs.
It ONLY checks the paragraph elements and creates an array containing them all, other elements will be included but not counted towards the position of the column divider. The next loop finds the center of the array and adds the column elements.
The above code would go in your functions.php file
All you need next is add in the css to style them up, note: at mobile width they will not need to be columns…
.columns { display: inline-block; width: 100%; vertical-align: top; } @media (min-width:782px){ .columns { width: 47.25%; width: calc(48% - 4px); } .columns.first { margin-right: 2%; } .columns.last{ margin-left: 2%; } }
This is a good solution for sites which have primarily text content, if other elements like headings, images, lists, blockquotes etc are used regularly in the post content another method will be required..