需要向Foreach循环中的第一个元素添加类

时间:2014-12-24 作者:TikaL13

我正在提取此特定帖子的所有附件,并将其显示在旋转木马中。问题是我需要给第一个项目一个活动类,这样引导旋转木马就可以工作了。

这是我的循环:

<?php foreach ( $attachments as $attachment ):
    $description = $attachment->post_content;
    echo \'<div class="item" data-description="\' . $description . \'">\';
    echo wp_get_attachment_image($attachment->ID, \'large\');
    echo \'</div>\';
    endforeach;
?>
我尝试过:

<?php $isFirst = true; ?>

<?php foreach ( $attachments as $attachment ):
    $description = $attachment->post_content;
    echo \'<div class="item\' . $isFirst ? \' active\' : \'\' . \'" data-description="\' . $description . \'">\';
    echo wp_get_attachment_image($attachment->ID, \'large\');
    echo \'</div>\';
    endforeach;
?>

1 个回复
最合适的回答,由SO网友:nkuldip 整理而成

Use below code

<?php 

    $isFirst = true;

    $i=1;   

    foreach ( $attachments as $attachment ):
    $description = $attachment->post_content;
    if($i==1)
    {
            echo \'<div class="item\'.$isFirst.\'" data-description="\' . $description . \'">\';
            echo wp_get_attachment_image($attachment->ID, \'large\');
            echo \'</div>\';
    }
    else
    {
            echo \'<div class="item" data-description="\' . $description . \'">\';
            echo wp_get_attachment_image($attachment->ID, \'large\');
            echo \'</div>\';
    }
        $i++;
      endforeach;
?>
结束