Wordpress posts in columns

2019-08-17 17:14发布

I am trying to create a wordpress theme. i would like to have three columns with post excerpts. But the problem is that they don't always have the same height (and i don't want them to), so when in one row a post is too high, the next row will start too far away.

Hmmm, i can really explain it, so i created this fiddle to show what i mean:

//in the fiddle there is html and css making a clear example of what i mean

http://jsfiddle.net/59qyD/1/

As you can see post id#5 is too long, so post #7 doesn't go any more under post #4.

What i would like is to find a solution where the post always "go up" to the previous post in that column. If possible, without any plugins...

Any ideas?

2条回答
走好不送
2楼-- · 2019-08-17 17:33

To create a dynamic column height no matter if it's images/posts/products, you can apply Masonry JS

This JS offers you the possibility to fit each new div under the previous div from the above line, and has a great effect of showing it.

查看更多
看我几分像从前
3楼-- · 2019-08-17 17:43

Here is a PHP + CSS based solution:

PHP:

$count = 0;
$count_total = 10; // or use dynamic count: count($all_posts)
$columns = 3;
foreach ( $all_posts as $k=>$v ) {
    $count++;
    $is_first_column = false; // always set to false, then set to true only when the condition matches!
    // Now check is this a post for the first column
    if( $count==1 || ($count-1)%$columns==0 ) { // check if it's 1st and every 4,7,10 post and place it in 'column 1'
        // set additional class for every post that need to be placed in the first column
        $is_first_column = true;
    }

    // Now you can add the additional class to the html markup:
    <article id="post-<?php the_ID(); ?>" class="post col<?php if( !empty( $is_first_column ) ) { echo ' column_1'; } ?>">


}

And then use CSS to clear the float for every .column_1.

CSS:

.column_1 {
    clear: both;
}

I used similar approach in multiple projects and it worked. The code above may need to me modified a bit to work for your specific theme, but I hope you'll get the main idea.

It will work immediately after page + CSS load (no waiting for JS to load)! :-)

查看更多
登录 后发表回答