DIV CSS 佈局教程網

用 AJAX 為 WordPress 實作文章列表與評論分頁
編輯:關於JavaScript     

文章列表頁分頁

一、引入 jQuery

整份方案由 jQuery 驅動,因此必須先載入函式庫。

二、確認 HTML 結構

列表頁(index.php、archive.php)需具備「容器 + 多個文章區塊」的結構:

<!-- 包含所有文章的容器 -->
<div id="content">
  <div class="post"></div>
  <div class="post"></div>
  <div class="post"></div>
</div>

三、加入預設導覽

因為 Ajax 每次抓的是「下一頁」,所以沿用 WordPress 內建的導航即可:

<div id="pagination">
  <?php next_posts_link(__('LOAD MORE')); ?>
</div>

四、Ajax 抓取下一頁

$("#pagination a").live("click", function () {
  $(this).addClass("loading").text("LOADING...");

  $.ajax({
    type: "POST",
    url: $(this).attr("href") + "#content",
    success: function (data) {
      var result   = $(data).find("#content .post");
      var nextHref = $(data).find("#pagination a").attr("href");

      $("#content").append(result.fadeIn(300));   // 淡入新內容
      $("#pagination a").removeClass("loading").text("LOAD MORE");

      if (nextHref != undefined) {
        $("#pagination a").attr("href", nextHref);
      } else {
        $("#pagination").remove();                // 是最後一頁,移除導航
      }
    }
  });
  return false;
});

五、改成捲動自動翻頁

var loading = false;   // 避免同一時間發出多個請求

$(window).bind("scroll", function () {
  if (loading) { return; }
  // 判斷捲軸是否接近頁面底部
  if ($(document).scrollTop() + $(window).height() > $(document).height() - 100) {
    loading = true;
    $("#pagination a").addClass("loading").text("LOADING...");

    $.ajax({
      type: "POST",
      url: $("#pagination a").attr("href") + "#content",
      success: function (data) {
        var result   = $(data).find("#content .post");
        var nextHref = $(data).find("#pagination a").attr("href");

        $("#content").append(result.fadeIn(300));
        if (nextHref != undefined) {
          $("#pagination a").attr("href", nextHref);
        } else {
          $("#pagination").remove();
        }
      },
      complete: function () { loading = false; }
    });
  }
});

這個 loading 旗標很重要:沒有它,捲動事件會連續觸發數十次請求。

六、美化導航

#pagination { padding: 20px 0 0 30px; }

#pagination .nextpostslink {
  width: 600px;
  color: #333;
  text-decoration: none;
  display: block;
  padding: 9px 0;
  text-align: center;
  font-size: 14px;
}
#pagination .nextpostslink:hover {
  background-color: #ccc;
  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
}
#pagination .loading {
  background: url("images/loading.gif") 240px 9px no-repeat;
  color: #555;
}

評論分頁

一、開啟 WordPress 評論分頁

後台 → 設定 → 討論,勾選分頁顯示評論並設定每頁則數。此處的數量只計算主評論,回覆不列入。

二、加入分頁導航

<nav id="comments-navi">
  <?php paginate_comments_links('prev_text=<&nbsp;上一頁&nbsp; ', 'next_text=&nbsp;&nbsp;下一頁&gt;'); ?>
</nav>

三、避免 SEO 重複內容

評論分頁會產生「正文相同、只有評論不同」的頁面,容易被視為重複內容。可在 header.php 加上:

<?php
if (is_single() || is_page()) {
  if (function_exists('get_query_var')) {
    $cpage = intval(get_query_var('cpage'));
    $commentPage = intval(get_query_var('comment-page'));
  }
  if (!empty($cpage) || !empty($commentPage)) {
    echo '<meta name="robots" content="noindex, nofollow" />' . "\n";
  }
}
?>

四、Ajax 化的評論分頁

先在評論列表前放一個載入提示元素:

<div class="comments">
  <h3 id="comments-list-title">Comments</h3>
  <div id="loading-comments"><span>Loading...</span></div>
  <ol class="comment_list">
    <li>...</li>
  </ol>
  <nav id="comments-navi">
    <a class="prev page-numbers" href="#">1</a> ...
  </nav>
</div>
var $body = (window.opera)
  ? (document.compatMode == "CSS1Compat" ? $('html') : $('body'))
  : $('html,body');

$('#comments-navi a').live('click', function (e) {
  e.preventDefault();
  $.ajax({
    type: "GET",
    url: $(this).attr('href'),
    beforeSend: function () {
      $('#comments-navi').remove();
      $('.comment_list').remove();
      $('#loading-comments').slideDown();
      $body.animate({ scrollTop: $('#comments-list-title').offset().top - 65 }, 800);
    },
    dataType: "html",
    success: function (out) {
      var result   = $(out).find('.comment_list');
      var nextlink = $(out).find('#comments-navi');
      $('#loading-comments').slideUp('fast');
      $('#loading-comments').after(result.fadeIn(500));
      $('.comment_list').after(nextlink);
    }
  });
});

載入提示的樣式:

#loading-comments {
  display: none;
  width: 100%;
  height: 45px;
  background: #a0d536;
  text-align: center;
  color: #fff;
  font-size: 22px;
  line-height: 45px;
}

實作提醒

  • live() 在 jQuery 1.9 之後已移除,新專案請改用 $(document).on('click', '#pagination a', handler) 的delegate 寫法。
  • 用字串組 HTML 時記得對留言內容做轉義,WordPress 評論使用者可自訂名稱與內容,不處理會有 XSS 風險。
  • 捲動自動載入需搭配 loading 旗標,否則會重複請求。
  • 若使用快取外掛,Ajax 回傳的頁面可能不是最新狀態,必要時在網址加上隨機參數。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved