我试图在foreach循环中使用下面的结构来获得结果,在每两幅图像之后,它将重复整个结构。
我有一些可以使用的基本知识,例如计数器++;和%2,但不知道语法以及如何在代码中使用它。
<?php
function dt_attached($postid=0, $size=\'thumbnail\', $attributes=\'\', $linksize=\'full\', $count=-1) {
if ($postid<1) $postid = get_the_ID();
if ($images = get_children(array(
\'post_parent\' => $postid,
\'post_type\' => \'attachment\',
\'numberposts\' => $count,
\'post_mime_type\' => \'image\',)))
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, \'thumbnail\');
$small_image = wp_get_attachment_image_src($image->ID, \'midium\');
$big_image = wp_get_attachment_image_src($image->ID, \'full\');
?>
<div class="mainrow">
<div class="block">
<a href=\'<?php echo $big_image[0]; ?>\' class=\'cloud-zoom-gallery\' title=\'Thumbnail 1\' rel="useZoom: \'zoom1\', smallImage: \'<?php echo $small_image[0]; ?>\' ">
<img src="<?php echo $attachment[0]; ?>" <?php echo $attributes; ?> />
</a>
</div>
<!--[I want to get two images in mainrow]-->
<div class="block">
<a href=\'<?php echo $big_image[0]; ?>\' class=\'cloud-zoom-gallery\' title=\'Thumbnail 1\' rel="useZoom: \'zoom1\', smallImage: \'<?php echo $small_image[0]; ?>\' ">
<img src="<?php echo $attachment[0]; ?>" <?php echo $attributes; ?> />
</a>
</div>
</div>
<?php //the_attachment_link($image->ID, false, true, false); ?>
<?php }
}
?>
所以我想要的是,如果有两个以上的图像,它将重复整个html结构。非常感谢你的帮助
最合适的回答,由SO网友:woony 整理而成
好的,基本上。你需要这个逻辑
<?php
if (($a % 2) == 1)
{ echo "$a is odd." ;}
if (($a % 2) == 0)
{ echo "$a is even." ;}
?>
你会像你一样循环。但确实要保留一个计数器。并进行相应检查。我没有测试就修改了你的代码。
<?php
function dt_attached($postid=0, $size=\'thumbnail\', $attributes=\'\', $linksize=\'full\', $count=-1) {
if ($postid<1) $postid = get_the_ID();
if ($images = get_children(array(
\'post_parent\' => $postid,
\'post_type\' => \'attachment\',
\'numberposts\' => $count,
\'post_mime_type\' => \'image\',)))
//declare some counter var
$counter = 0;
foreach($images as $image) {
$attachment=wp_get_attachment_image_src($image->ID, \'thumbnail\');
$small_image = wp_get_attachment_image_src($image->ID, \'midium\');
$big_image = wp_get_attachment_image_src($image->ID, \'full\');
// everytime raise your counter + 1
$counter= $counter+1; //you can use $counter+=1; also
?>
// this part you only want every 2 rows
<?php
if (( $counter % 2) == 1){
if ($counter > 1) {
$uneven = true;
echo \'</div>\' ; // your closing div
}
echo \'<div class="mainrow">\'; // opening div
}
//this part you want every time so no need to check it
?>
<div class="block">
<a href=\'<?php echo $big_image[0]; ?>\' class=\'cloud-zoom-gallery\' title=\'Thumbnail 1\' rel="useZoom: \'zoom1\', smallImage: \'<?php echo $small_image[0]; ?>\' ">
<img src="<?php echo $attachment[0]; ?>" <?php echo $attributes; ?> />
</a>
</div> <?php
if ($uneven && $counter == count($images)){ // $count is your amount of attach ?>
<div class="block">
<!--your empty image code -->
</a>
</div> <?php } ?>
</div>
<?php }
}
?>