0

I'm pulling all attachments for this particular post and displaying them in a carousel. Problem is I need to give the first item a class of active so bootstrap carousel will work.

Here is my loop:

<?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;
?>

I've tried:

<?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 Answer 1

3

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;
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.