我很难找到实现这一目标的最佳方法。我试图一次加载两张照片到一个用作幻灯片包装的。目前,我正在重复大量代码,每次都只是手动设置偏移量。
我当前的代码可以工作,但它非常笨拙。下面是它的样子:
<div id="engagement">
<div>
<div class="row">
<?php
$images = new WP_Query( array(
\'post_parent\' => get_the_ID(),
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ID\',
\'offset\' => 0,
\'posts_per_page\' => 2, // show two images at a time
\'update_post_term_cache\' => false,
) );
foreach ($images->posts as $image) {
?>
<div class="six columns mobile-two">
<?php echo wp_get_attachment_image( $image->ID, \'full\' ); // get the image ?>
</div>
<?php
}
?>
</div>
<div class="row">
<?php
$images = new WP_Query( array(
\'post_parent\' => get_the_ID(),
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ID\',
\'offset\' => 2,
\'posts_per_page\' => 2, // show two images at a time
\'update_post_term_cache\' => false,
) );
foreach ($images->posts as $image) {
?>
<div class="six columns mobile-two">
<?php echo wp_get_attachment_image( $image->ID, \'full\' ); // get the image ?>
</div>
<?php
}
?>
</div>
<div class="row">
<?php
$images = new WP_Query( array(
\'post_parent\' => get_the_ID(),
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ID\',
\'offset\' => 4,
\'posts_per_page\' => 2, // show two images at a time
\'update_post_term_cache\' => false,
) );
foreach ($images->posts as $image) {
?>
<div class="six columns mobile-two">
<?php echo wp_get_attachment_image( $image->ID, \'full\' ); // get the image ?>
</div>
<?php
}
?>
</div>
</div>
看来必须有更好的方法来做到这一点。
谢谢
最合适的回答,由SO网友:Ed Burns 整理而成
是的,效率很低。以下是重写:
<div id="engagement">
<?php
$images = new WP_Query( array(
\'post_parent\' => get_the_ID(),
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ID\',
\'offset\' => 0,
\'posts_per_page\' => 6, // show six images total
\'update_post_term_cache\' => false,
) );
$count = 0;
foreach ($images->posts as $image) {
if($count % 2==0) echo "<div><div class=\'row\'>";
echo "<div class=\'six columns mobile-two\'>
echo wp_get_attachment_image( $image->ID, \'full\' );
echo "</div>";
$count++;
if($count % 2==0) echo "</div></div>";
}
?>
</div>
这里的想法是只使用一个查询来获取所有六个图像,然后循环遍历它们。我们使用模化运算符(%)来确定何时处理奇数项或偶数项,以便知道何时为行添加起始和结束div元素。
代码是刚刚从我的头上,所以它是目前未经测试。。。