jehzlau
jehzlau

Reputation: 627

Foreach loop, offset or skip first post in the loop

I'm trying to figure this out for hours but I can't. I just want to show the second post and skip the first one, just like the Wordpress offset function. I'm using AW blog extension for Magento and I want to skip the first post in the recent blog posts. Below is my modified code showing one post recent post in a homepage block. I just want to create another block that will show the second recent post. :(

<?php $posts = $this->getPosts(); ?>
<div id="messages_product_view">
    <?php Mage::app()->getLayout()->getMessagesBlock()->    setMessages(Mage::getSingleton('customer/session')->getMessages(true)); ?>
    <?php echo Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml(); ?>
</div>

<?php 
 foreach ($posts as $post):
 if ($i++ >= 1) break;
?>


    <div class="postWrapper">
        <div class="postTitle">
            <h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
        </div>
        <div class="postContent"><?php echo $post->getPostContent(); ?></div>
    </div>
<?php endforeach; ?>

Upvotes: 0

Views: 1845

Answers (3)

Jorge Campos
Jorge Campos

Reputation: 23381

I will recommend you to check the count and after printing it stop the loop, otherwise it will loop the entire array to the end and print just the second iteration.

$i=0;    
foreach ($posts as $post){
    if ($i==1) {
       //print your div here
       $i++; //added here after edit.
       continue;
    }else if ( $i>1 ){
        break;
    }
    $i++;
}

This way it will only iterate twice.

Upvotes: 1

TBI
TBI

Reputation: 2809

Try this -

<?php $i=1;
 foreach ($posts as $post):
 if ($i > 1) {
?>
    <div class="postWrapper">
        <div class="postTitle">
            <h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
        </div>
        <div class="postContent"><?php echo $post->getPostContent(); ?></div>
    </div>
<?php }
$i++;
endforeach; ?>

Upvotes: 0

Dustin Cochran
Dustin Cochran

Reputation: 1165

Try changing:

foreach ($posts as $post):
if ($i++ >= 1) break;

to:

//set $i outside of loop
$i=0;    
foreach ($posts as $post):
if ($i==0) {
  $i++;
  //skip the first record
  continue;
}

Upvotes: 0

Related Questions