我已经找到了一些关于如何循环浏览帖子的信息,但我还没有找到确切的信息。
基本上,我希望在我的主页上输出4行帖子(最多10篇帖子)。
第一行:
<div class="tiles">
<div class="tile"></div>
<div class="tile large"></div>
</div>
第二行:
<div class="tiles">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
第三排:
<div class="tiles">
<div class="tile large"></div>
<div class="tile"></div>
</div>
第四排:
<div class="tiles">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
这是一个显示所需布局的线框。
SO网友:Maxim Sarandi
让我们看看你的结构。您有2个块,每个块有2条线。第一排有2根柱子,第二排有3根柱子。看见screen
首先,我们将数组分块到每个分块5个;下一步,我们需要用5个帖子到2个和3个帖子来分隔每个数组。
然后打印所有这些内容,并为每一个块添加特殊类。
所有代码如下所示
global $wp_query;
$posts = $wp_query->posts; // get posts from global query for home page
$chunks = [];
$i = 0;
$five_elems = array_chunk( $posts, 5 ); // Split an array into chunks 5 per array
foreach ( $five_elems as $five ) {
$lines = array_chunk( $five, 2 ); // split our chunked array (5 per array) to 2-2-1
$res = array_merge( $lines[1], $lines[2] ); // merge 2-1 to 3 elements
unset( $lines[1] ); // delete second `2`
unset( $lines[2] ); // delete last `1`
$lines[1] = $res; // create chunked array with 2-3 elems
/*
* Save all data to this like:
*
array (size=2)
0 =>
array (size=2)
0 =>
array (size=2)
0 =>
object(WP_Post)[1286]
...
1 =>
object(WP_Post)[1287]
...
1 =>
array (size=3)
0 =>
object(WP_Post)[1288]
...
1 =>
object(WP_Post)[1289]
...
2 =>
object(WP_Post)[1290]
...
1 =>
array (size=2)
0 =>
array (size=2)
0 =>
object(WP_Post)[1291]
...
1 =>
object(WP_Post)[1292]
...
1 =>
array (size=3)
0 =>
object(WP_Post)[1293]
...
1 =>
object(WP_Post)[1294]
...
2 =>
object(WP_Post)[1421]
...
*/
$chunks[] = $lines;
}
foreach ( $chunks as $posts ) {
++ $i;
// create class for every second element and other
$class = $i % 2 === 0 ? \'small-right\' : \'small-left\';
// your line with 2 posts (small and large)
echo \'<div class="tiles \' . $class . \'">\';
foreach ( $posts[0] as $block ) {
echo \'<div class="tile">\' . $block->ID . \'</div>\';
}
echo \'</div>\';
// your 3 per line posts
echo \'<div class="tiles">\';
foreach ( $posts[1] as $block ) {
echo \'<div class="tile">\' . $block->ID . \'</div>\';
}
echo \'</div>\';
}
将此代码插入
home.php
相反
while(have_posts())..
环
记住,这是一个简单的例子。我认为这不是最好的解决办法。我希望这段代码能帮助你理解我。