abbas_arezoo
abbas_arezoo

Reputation: 1078

Wordpress/ACF relationship field: wrap last two posts in a separate div

I'm using Advanced Custom Fields and I have a relationship field that allows the user to select three posts to show on a page.

I'd like to be able to wrap the last two posts selected in a seperate <div> to the first post.

Here's an example loop that I'm using:

<?php 

$items = get_field('my_items');
if( $items ):

?>

<div class="my-items">
  <?php foreach( $items as $item ): ?>
    <div class="item">...</div>
  <?php endforeach; ?>
 </div>

<?php endif; ?>

Which gives me:

<div class="my-item">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
</div>

Here's my desired result:

<div class="my-item">
  <div class="item">...</div>
  <div>
    <div class="item">...</div>
    <div class="item">...</div>
  </div>
</div>

Is this possible? If so, is it also possible to do this in reverse too, so the first two items are wrapped and last one isn't?

Upvotes: 1

Views: 121

Answers (1)

McNab
McNab

Reputation: 6777

The easiest way to do things like this is just initialise a counter and then use it in conditionals within your loop, incrementing the counter at the end. The code below does what you want;

    <?php 

    $items = get_field('my_items');
    if( $items ):
    $counter = 0;
    ?>

    <div class="my-items">
      <?php foreach( $items as $item ): ?>
        <?php if ($counter == 1 ) { echo '<div>'; } ?>
        <div class="item">...</div>
        <?php if ($counter == 2 ) { echo '</div>'; } ?>
        <?php counter++; ?>
      <?php endforeach; ?>
     </div>

    <?php endif; ?>

If you wanted to wrap the first two items instead, then the code would be;

    <div class="my-items">
      <?php foreach( $items as $item ): ?>
        <?php if ($counter == 0 ) { echo '<div>'; } ?>
        <div class="item">...</div>
        <?php if ($counter == 1 ) { echo '</div>'; } ?>
        <?php counter++; ?>
      <?php endforeach; ?>
     </div>     

Upvotes: 1

Related Questions