WordPress 使用 cookie 製作使用者瀏覽紀錄

WordPress 使用 cookie 製作使用者瀏覽紀錄

功能論述:

「使用者瀏覽紀錄」功能,可以幫助 使用者 快速的找到曾經閱讀過的文章,對於 更新速度快 與有著 大量文章篇幅 的 網站 與 應用 當中,在使用者體驗上有著十分出眾且直接的幫助


開發方向:

已開發者的角度而言,我們要先做的事如下:

  • 使用者 點擊過的文章 存入到 瀏覽器的 cookie 中
  • 再將 存入 cookie 裡的文章,Query 到我們的頁面之中

以上兩點是主要方向


取得當前 文章 的 ID :

當使用者在進入文章內頁時,取得 文章 的 ID , 將此 ID 作為變數傳給 JavaScript 的檔案

function.php :

<?php
function history_cookie_enqueue_script(){
    global $post;

    if(!is_single()){
        $postID = 0;
    }else {
        $postID = $post->ID;
    }
    wp_enqueue_script('cookie_history', get_stylesheet_directory_uri() . '{檔案路徑/檔案名稱.js}');
    wp_localize_script('cookie_history', 'postID', $post->ID);
}
add_action('wp_enqueue_scripts', 'history_cookie_enqueue_script');
?>

在這部分使用 is_single() 做了一個小判斷,因為我們只需要針對 文章內頁 進行存取就行了


JavaScript 存取 cookie:

cookie-history.js :

首先我們需要這 兩個 function 來方便 存取 我們 cookie 的資料 :

/**
 * [setCookie description]
 * @param {string} cname  [cookie name]
 * @param {string} cvalue [cookie value]
 * @param {number} exdays [save date]
 */
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

/**
 * [getCookie description]
 * @param  {string} cname [you want return the name of the data]
 * @return {string}       [return the json string of the data value]
 */
function getCookie(cname) {

    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');

    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
}

建立 cookie 與 更新 cookie :


if(getCookie('history_query') == null){ //default cookie data var data = '{}'; //setCookie setCookie('history_query',data,1); } else { // update cookie code is here //update cookie setCookie('history_query',JSON.stringify(updateData),1); }

我們並沒有辦法對現有的 cookie 進行編輯,所以必須使用重新再建立相同的 cookie 名稱來去複寫他

將從 function.php 取得的 postid , 寫入 cookie

var getID = postID;

if(getCookie('history_query') == null){

  //default cookie data
  var data = '{}';

  //setCookie
  setCookie('history_query',data,1);

} else {
  //get cookie value to json object
  var updateData = getCookie('history_query');

  //string to json object
  updateData = JSON.parse(updateData);

  //json object to array
  updateData = Object.keys(updateData).map(function(_) { return updateData[_]; });


  //filter repeat nid
  updateData = updateData.filter(chickNid);

  function chickNid($array){
    return $array['nid'] != getID;
  }

  //create new data
  if(getID){
    updateData[updateData.length] = {'nid':getID}; 
  }

  //update cookie
  setCookie('history_query',JSON.stringify(updateData),1);
}

透過 JavaScript 將 JSON Object 轉為 Arrary,進行 cookie 的寫入
使用 陣列(Array)的方法,filter,過濾掉重複的文章

到此 cookie 的設定算是完成了


在 WordPress 的 template.php 中進行 Query

最後的一部分,我們只要在 迴圈中 使用 $_COOKIE[$cookie_name]) 取得 cookie 中的資料,就可以搭配 WordPress 內建提供的 wp_query() 的方法來取出我們需要的資料就行了

your template.php 檔案:

<!--get cookie data-->
<?php $data = json_decode(stripslashes($_COOKIE["history_query"]), true);?>

<div class ="history_block">
  <?php foreach ($data as $key => $value):?>
    <!--get the nid for wp_query -->
    <?php $nid = $data[$key]['nid']; ?>

    <?php $the_query = new WP_Query( array( 'p' => $nid ) );?>
     <?php if ( $the_query->have_posts() ) : ?>
       <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

         <!--your html structure-->
         <div class ="title"><?php the_title(); ?></div>
         <div class ="body"><?php the_content(); ?></div>

       <?php endwhile; ?>
     <?php endif; ?>
  <?php endforeach ?>
</div>

結語:

上述的紀錄已經可以獨立完成 「使用者瀏覽紀錄」 的功能,不過就到目前為止而言,有只不過完成雛形的部分而已,後續還可以延續製作許多客製化的功能,歡迎留言討論

Facebook 功能: