如何获取Magento博客文章页面中的上一个和下一个链接


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

在Magento 1.9.1上,我有一个博客文章模板,它包含以下内容:

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

在模板的底部有下一篇和上一篇文章的链接:

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

这很好用,但有一个问题;它不考虑文章是启用还是禁用。

有没有办法排除"禁用"的文章?

将您的代码替换为以下代码,并进行一些修改,如将"id"替换为post表的主键字段,将"status"字段替换为status列名。

<?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();
    }
  ?>

并用替换您的html代码

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

希望这对你有帮助。