如何在 Magento 博客 post 页面中获取上一个和下一个链接?

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

在 Magento 1.9.1 上,我有一个博客 post 模板,其中包含以下内容:

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

这工作正常,但有一个问题;它不考虑文章是启用还是禁用。

是否有办法排除 'disabled' 篇文章?

将您的代码替换为以下代码并进行一些修改,例如将 'id' 替换为 post table 的主键字段,将 '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;?>

希望对您有所帮助。