Adam Adam - 2 months ago 15
PHP Question

How can I get previous and next links in Magento blog post pages?

On Magento 1.9.1, I have a blog post template that has the following:

<?php $post = $this->getPost(); ?>
<?php $next = Mage::getModel('blog/post')->load($post->getId()+1); ?>
<?php $prev = Mage::getModel('blog/post')->load($post->getId()-1); ?>


and the at the bottom of the template there are links for the next and previous article:

<a href="/blog/<?php echo $prev->getIdentifier(); ?>" class="prev">< Previous</a>
<a href="/blog/<?php echo $next->getIdentifier(); ?>" class="next">Next ></a>


This works fine but with one problem; it doesn't take into account if the article is enabled or disabled.

Is there a way for it to exclude 'disabled' articles?

Answer

Replace your code with following code with some modifications like replace 'id' with primary key field for post table and same for 'status' field with status column name.

<?php $post = $this->getPost(); ?>  
<?php  
    $prevCollection = Mage::getModel('blog/post')->getCollection()
          ->addFieldToFilter('id', array('lt' => $post->getId()))
          ->addFieldToFilter('status', 'enabled')
          ->addOrder('id','DESC');
    $prevCollection->getSelect()->limit(1);
    if($prevCollection->count()){
      $prev = $prevCollection->getFirstItem();
    }

    $nextCollection = Mage::getModel('blog/post')->getCollection()
         ->addFieldToFilter('id', array('gt' => $post->getId()))
         ->addFieldToFilter('status', 'enabled');
    $nextCollection->getSelect()->limit(1);
    if($nextCollection->count()){
      $next = $nextCollection->getFirstItem();
    }
  ?>

and replace your html code with

    <?php if(isset($prev) && $prev->getId()):?>
          <a href="/blog/<?php echo $prev->getIdentifier(); ?>" class="prev">< Previous</a>
    <?php endif;?>
    <?php if(isset($next) && $next->getId()):?>
          <a href="/blog/<?php echo $next->getIdentifier(); ?>" class="next">Next ></a>
    <?php endif;?>

Hope this will help you.