Drupal 7 实现上一篇下一篇的简单方法

2016-02-22    编辑:lanve     点击(
在建个人小站[阿亮php笔记]时,想在文章页面实现“上一篇,下一篇”的效果,Drupal 7 是没有默认带这个功能的,网上也有写好的模块,不过个人感觉,这么一个小功能还装个模块的话,太浪费性能的,反正就两条SQL搞定,就自己随便写一下吧。

在模板/sites/all/themes/liuzhiliang.com/template.php文件上加个函数

 代码如下 复制代码

/**
 * myNodePrevNext
 * 文章上一篇下一篇
 * $nid - 节点id
 * $type - 节点类型
 */
function myNodePrevNext($nid, $type)
{
    $output = '<ul>';

    $sql_previous = "SELECT n.nid, n.title, url.alias "
                  . "FROM {node} AS n "
                  . "LEFT JOIN {url_alias} AS url "
                  . "ON concat('node/',n.nid)=url.source "
                  . "WHERE n.nid < :nid AND n.type = :type "
                  . "ORDER BY n.nid DESC "
                  . "LIMIT 0, 1";

    $result_previous = db_query($sql_previous, array(':nid' => $nid, ':type' => $type));

    $strings = array();

    foreach ($result_previous as $data)
    {
        $data->url = ($data->alias) ? $data->alias : '/node/' . $data->nid;

        $output .= '<li>上一篇:'
                . '<a href="' . $data->url . '" title="' . $data->title . '">'
                . $data->title
                . '</a>'
                . '</li>';
    }

    $sql_next = "SELECT n.nid, n.title, url.alias "
              . "FROM {node} AS n "
              . "LEFT JOIN {url_alias} AS url "
              . "ON concat('node/',n.nid)=url.source "
              . "WHERE n.nid > :nid AND n.type = :type "
              . "ORDER BY n.nid ASC "
              . "LIMIT 0, 1";
    $result_next = db_query($sql_next, array(':nid' => $nid, ':type' => $type));

    $strings = array();

    foreach ($result_next as $data)
    {
        $data->url = ($data->alias) ? $data->alias : '/node/' . $data->nid;

        $output .= '<li>下一篇:'
                . '<a href="' . $data->url . '" title="' . $data->title . '">'
                . $data->title
                . '</a>'
                . '</li>';
    }

    $output .= '</ul>';

    return $output;
}

再到/sites/all/themes/liuzhiliang.com/templates/node.tpl.php加上下面这段代码,具体位置看自己喜欢,我是在文章底部显示,所以在回在了<div class="content clearfix"<?php print $content_attributes; ?>>后面

 代码如下 复制代码

<?php if (!$teaser) : ?>
  <div class="previous_next">
    <?php print myNodePrevNext($node->nid, $node->type); // 上下篇 ?>
  </div>
<?php endif; ?>

原文来自:啊亮博客 http://liuzhiliang.com/node/63