2columns

WordPress: Display Content in multiple Columns

Recently I had to create a website which displays the content in 2 columns.

While CSS 3 is capable of doing this on its own with the new Grid Position Module, a lot of browsers do not support this functions yet, so I needed to add a little extra markup to the output which is generated via the_content() to get the following result:


To get this result we need to filter the_content() before output with a custom function and add 2 divs to the output, which we style with CSS later on. So Ladys and Gentleman please open the functions.php file of your current WordPress Theme.

What functions.php does is let you create functions you can reuse in your theme. It works similar to a plugin file, being loaded when the theme is first loaded.

First of all: here you can see the whole code we need to filter our content, step by step description follows:

function my_multi_col($content){
$columns = explode('<h2>', $content);

$i = 0;

	foreach ($columns as $column){
	if (($i % 2) == 0){
		$return .= '<div class="content_left">' . "\n";
		if ($i > 1){
		$return .= "<h2>";
	} else{
		$return .= '<div class="content_right">' . "\n <h2>";
	}
		$return .= $column;
		$return .= '</p></div>';
		$i++;
	}

	if(isset($columns[1])){
	    $content = wpautop($return);
	}else{
	    $content = wpautop($content);
	}
	echo $content;
}
add_filter('the_content', 'my_multi_col');

What we do first is define a delimiter and split the whole content at specific points. I wanted to create a new column whenever a h2 tag was found.

$columns = explode('<h2>', $content);

The result is stored in an array which we will use to create a new $content string. To access each array item we will use a foreach loop:

        $i = 0;

	foreach ($columns as $column){
        $i++;
	}

You should have noticed the variable $i by now, we will use it to check if the current content part should be stored in a left column or right column div. To accomplish this we simply use the modulo operation ( $i % 2).

The modulo operator divides the first integer by the second and returns the remainder. Since we divide by 2 there are only 2 possible values to return: 0 and 1. If zero is returned we need a left content div, if 1 is returned a right content div:

        $i = 0;
	foreach ($columns as $column){
            if (($i % 2) == 0){
                $return .= '<div class="content_left">' . "\n";
            }else{
                $return .= '<div class="content_right">' . "\n";
            }
        $i++;
	}

Since the explode function we used earlier strips away our <h2> opening tags we need to add them to the code again, but we must be careful were to add them: We always need an opening tag in the right column and always need an opening tag in the left column except for the first time!

$i = 0;

	foreach ($columns as $column){
	if (($i % 2) == 0){
		$return .= '<div class="content_left">' . "\n";
		if ($i > 1){
		$return .= "<h2>";
	} else{
		$return .= '<div class="content_right">' . "\n <h2>";
	}

	}

After adding the opening tags we simply put in the exploded $content parts and close the current <p> (automatically generated by WordPress) and <div> tag. After creating our new content string which is currently stored as a whole in $return we pass it to the wpautop which automatically adds formating to the string, store it in $content and then output it with echo, but ONLY if there was an h2 tag found. Otherwise we don’t need a second column and display the_content() without modifications.

$i = 0;

	foreach ($columns as $column){
	if (($i % 2) == 0){
		$return .= '<div class="content_left">' . "\n";
		if ($i > 1){
		$return .= "<h2>";
	} else{
		$return .= '<div class="content_right">' . "\n <h2>";
	}
		$return .= $column;
		$return .= '</p></div>';
		$i++;
	}

        if(isset($columns[1])){
	    $content = wpautop($return);
	}else{
	    $content = wpautop($content);
	}	echo $content;
}

Last but not least we have to tell WordPress when to activate our function. This is simply done with “add_filter”

add_filter('the_content', 'my_multi_col');

Now whenever $content contains any h2 items they will be put in different divs . Just add some basic CSS and you are done:

.content_right, .content_left{
float:left;
width:45%;
}

.content_left{
padding-right:5%;
}

The function we created is far from perfect, but the main goal of this tutorial is to show you how you can modify the output of the WordPress generated content in an easy way. Have fun doing so ;)

Tags: ,
73 replies
« Older Comments
  1. Steve says:

    This is a great tutorial, really useful! Do you know of a way to automatically generate another column if the post is of a certain length rather than when an h2 tag is used?

    Thanks for the post, really good work.

  2. Daniel says:

    Hi, i want to show posts from a specific category in columns and rows. Let me give you an example: I have a category named videos, where each post is a video. On the videos category page, i would like the posts (videos) to show in 3 columns and rows, just like a video site. Is it possible to do that with that code? Can you help me? Thanks a lot.

  3. WebpageLottery says:

    Good idea but doesn’t work in my case because I installed a rating plugin which will add a rating block on every post. If I overwrite the_content function, my rating is not showing up anymore =(

  4. Andrea says:

    Hi, i copy rhe php in function php and everthing ok but whei i insert a h2 title in a page for example (about) the content are not split in 2 col why? maybe the filter?

  5. Dario Shelly says:

    Do not repeat the tactics which have gained you one victory, but let your methods be regulated by the infinite variety of circumstances “Sun Tzu c. 490 BC, Chinese military strategist “

  6. Richard Brown says:

    Hi

    Thanks for the post. I am trying to style a shopping cart and wondered whether it would be possible to use your technique to float content left and right. i.e. float text left, float images right. I would use a custom field to declare the image element.

    Thanks for any help.

    Rich

Trackbacks & Pingbacks

  1. [...] 12.How To Display Content In Multiple Columns [...]

  2. [...] If you need something a little more “universal” than what is currently available with CSS3, we can always dig into our template files, modify things at the PHP/(X)HTML level, and then style accordingly. Here is the technique provided by Kriesi.at: [...]

  3. [...] If you need something a little more “universal” than what is currently available with CSS3, we can always dig into our template files, modify things at the PHP/(X)HTML level, and then style accordingly. Here is the technique provided by Kriesi.at: [...]

  4. [...] 12.How To Display Content In Multiple Columns [...]

  5. [...] 12.How To Display Content In Multiple Columns [...]

  6. [...] Se quiser aprofundar mais o assunto pode consultar o artigo original da Kriesi. [...]

  7. [...] quiser aprofundar mais o assunto pode consultar o artigo original da Kriesi. blog comments powered by Disqus var disqus_url = [...]

  8. [...] 12.How To Display Content In Multiple Columns [...]

  9. [...] to www.kriesi.at for contributing this great function to the community! VN:F [1.8.0_1031]please wait…Rating: [...]

  10. [...] denne funktion anvendt ved at søge på google: Se anvendelsen her iøvrigt en funktion der minder om [...]

  11. [...] kriesi.at Share this on del.icio.usBuzz up!Stumble upon something good? Share it on StumbleUponShare this on [...]

  12. [...] que muchos apreciarán, pues permite mostrar el contenido de los posts en dos columnas, dando un aspecto de diario digital a tu sitio creado con [...]

  13. [...] site). All the blocks of content are unique to that page. This solution was heavily inspired by a post at kriesi.at, but I’ve modified it with the help of Chris Bratlien to make as many content areas as you [...]

  14. [...] WordPress: Content Output in 2 Columns | Kriesi.at – new media design [...]

  15. [...] que muchos apreciarán, pues permite mostrar el contenido de los posts en dos columnas, dando un aspecto de diario digital a tu sitio creado con [...]

  16. [...] to http://www.kriesi.at for contributing this great function to the community! If you enjoyed this article, please [...]

  17. [...] page. All three blocks of content are unique to that page. This solution was heavily inspired by a post at kriesi.at, but I’ve modified it with the help of Chris Bratlien to make as many content areas as you [...]

  18. [...] We had a look around and we found a potential solution on this blog post. [...]

  19. [...] en una o dos columnas y quieres cambiarlo a más pero que sea usable, te invito a que revises este tutorial que explica cómo trabajar el código haciendo uso de CSS3 y respetando los estándares de la [...]

  20. [...] questo post viene spiegato come spezzare e visualizzare il testo di un articolo su due [...]

  21. [...] Using excerpts in templates Cool plugins, including disabling formatting, twitter, article list Removing <p> tags 1 Removing <p> tags 2 Multiple columns in posts [...]

  22. [...] en una o dos columnas y quieres cambiarlo a más pero que sea usable, te invito a que revises este tutorial que explica cómo trabajar el código haciendo uso de CSS3 y respetando los estándares de la [...]

Comments are closed.