手把手教你如何在商品详情页显示最近浏览过的商品列表

    今天给大家带来的文章有点简单,也有点复杂。简单是指功能比较简单,复杂是指代码理解起来比较复杂。直接说功能吧!在upsell中,会有related products模块,很多人有另外一个需求,recently viewed products。我找了一个相对来讲比较简单的版本,修改了一下PC端与手机端的适配,截图给大家:

    这个功能会记录下用户访问的产品页面,由于是简单版本,始终显示的是最新访问的四个产品,没有做额外的设置接口。比如轮播,比如页面显示多少个产品,也没有添加ATC按钮,这些改动涉及到的修改处太多了,并不适合没有代码经历的人来做。本篇教程以Brooklyn主题为例,适用于Shopify官方免费主题。

01

添加jquery.products.js文件

    点击Online Store -> Themes -> Current Theme -> Edit Code,在Assets目录下,创建jquery.products.js文件,保存空文件,如下图:

    将下面的代码黏贴至上面创建的文件中,点击保存。

/**

 * Cookie plugin

 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)

 * Dual licensed under the MIT and GPL licenses:

 * http://www.opensource.org/licenses/mit-license.php

 * http://www.gnu.org/licenses/gpl.html

 */

jQuery.cookie=function(b,j,m){if(typeof j!=”undefined”){m=m||{};if(j===null){j=””;m.expires=-1}var e=””;if(m.expires&&(typeof m.expires==”number”||m.expires.toUTCString)){var f;if(typeof m.expires==”number”){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e=”; expires=”+f.toUTCString()}var l=m.path?”; path=”+(m.path):””;var g=m.domain?”; domain=”+(m.domain):””;var a=m.secure?”; secure”:””;document.cookie=[b,”=”,encodeURIComponent(j),e,l,g,a].join(“”)}else{var d=null;if(document.cookie&&document.cookie!=””){var k=document.cookie.split(“;”);for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+”=”)){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};

/**

 * Module to show Recently Viewed Products

 * Copyright (c) 2014 Caroline Schnapp (11heavens.com)

 * Dual licensed under the MIT and GPL licenses:

 * http://www.opensource.org/licenses/mit-license.php

 * http://www.gnu.org/licenses/gpl.html

 */

 Shopify.Products = (function() {

   var config = { 

     howManyToShow: 3,

     howManyToStoreInMemory: 10, 

     wrapperId: ‘recently-viewed-products’, 

     templateId: ‘recently-viewed-product-template’,

     onComplete: null

   };   

   var productHandleQueue = [];

   var wrapper = null;

   var template = null;

   var shown = 0;

   var cookie = {

     configuration: {

       expires: 90,

       path: ‘/’,

       domain: window.location.hostname

     },

     name: ‘shopify_recently_viewed’,

     write: function(recentlyViewed) {

       jQuery.cookie(this.name, recentlyViewed.join(‘ ‘), this.configuration);

     },

     read: function() {

       var recentlyViewed = [];

       var cookieValue = jQuery.cookie(this.name);

       if (cookieValue !== null) {

         recentlyViewed = cookieValue.split(‘ ‘);

       }

       return recentlyViewed;        

     },

     destroy: function() {

       jQuery.cookie(this.name, null, this.configuration);

     },

     remove: function(productHandle) {

       var recentlyViewed = this.read();

       var position = jQuery.inArray(productHandle, recentlyViewed);

       if (position !== -1) {

         recentlyViewed.splice(position, 1);

         this.write(recentlyViewed);

       }       

     }

   };  

   var finalize = function() {

     wrapper.show();

     // If we have a callback.

     if (config.onComplete) {

       try { config.onComplete() } catch (error) { }

     }  

   };   

   var moveAlong = function() {

     if (productHandleQueue.length && shown < config.howManyToShow) {

       jQuery.ajax({

         dataType: ‘json’,

         url: ‘/products/’ + productHandleQueue[0] + ‘.js’,

         cache: false,

         success: function(product) {

           var moneyFormat = ‘${{amount}}’;

           if (product.price) {

             product.price = theme.Currency.formatMoney(product.price, moneyFormat);

           }

           if (product.compare_at_price) {

             product.compare_at_price = theme.Currency.formatMoney(product.compare_at_price, moneyFormat);

           }

           template.tmpl(product).appendTo(wrapper); 

           productHandleQueue.shift();

           shown++;

           moveAlong();

         },

         error: function() {

           cookie.remove(productHandleQueue[0]);

           productHandleQueue.shift();

           moveAlong();

         }

       });

     }

     else {

       finalize();

     }     

   };  

   return {   

     resizeImage: function(src, size) {

       if (size == null) {

         return src;

       }

       if (size == ‘master’) {

         return src.replace(/http(s)?:/, “”);

       }

       var match  = src.match(/.(jpg|jpeg|gif|png|bmp|bitmap|tiff|tif)(?v=d+)?/i);

       if (match != null) {

         var prefix = src.split(match[0]);

         var suffix = match[0];

         return (prefix[0] + “_” + size + suffix).replace(/http(s)?:/, “”)

       } else {

         return null;

       }

     },

     showRecentlyViewed: function(params) {

       var params = params || {};

       // Update defaults.

       jQuery.extend(config, params);

       // Read cookie.

       productHandleQueue = cookie.read();       

       // Template and element where to insert.

       template = jQuery(‘#’ + config.templateId);

       wrapper = jQuery(‘#’ + config.wrapperId);      

       // How many products to show.

       config.howManyToShow = Math.min(productHandleQueue.length, config.howManyToShow);

       // If we have any to show.

       if (config.howManyToShow && template.length && wrapper.length) {

         // Getting each product with an Ajax call and rendering it on the page.

         moveAlong();    

       }

     },

     getConfig: function() {

       return config;

     },

     clearList: function() {

       cookie.destroy();      

     }, 

     recordRecentlyViewed: function(params) {

       var params = params || {};

       // Update defaults.

       jQuery.extend(config, params);

       // Read cookie.

       var recentlyViewed = cookie.read();

       // If we are on a product page.

       if (window.location.pathname.indexOf(‘/products/’) !== -1) {

         // What is the product handle on this page.

         var productHandle = window.location.pathname.match(//products/([a-z0-9-]+)/)[1];

         // In what position is that product in memory.

         var position = jQuery.inArray(productHandle, recentlyViewed);

         // If not in memory.

         if (position === -1) {

           // Add product at the start of the list.

           recentlyViewed.unshift(productHandle);

           // Only keep what we need.

           recentlyViewed = recentlyViewed.splice(0, config.howManyToStoreInMemory);

         }

         else {

           // Remove the product and place it at start of list.

           recentlyViewed.splice(position, 1);

           recentlyViewed.unshift(productHandle);              

         }

         // Update cookie.

         cookie.write(recentlyViewed);

       }   

     }

   };

 })();

02

添加recently-viewed.liquid

    在Snippets目录下,创建recently-viewed.liquid文件,点击create,如下图:

    添加下属代码在上述建立的文件中 ,点击保存。

{{ ‘//ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js’ | script_tag }}

{{ ‘jquery.products.js’ | asset_url | script_tag }}

<div id=”recently-viewed-products” class=”collection clearfix” style=”display:none”>

  <h2>Recently Viewed Products</h2>

</div>

{% raw %}

<script id=”recently-viewed-product-template”  type=”text/x-jquery-tmpl”>

<div id=”product-${handle}” class=”product”>

  <div class=”image”>

    <a href=”${url}”>

      <img src=”${Shopify.Products.resizeImage(featured_image, “large”)}” />

    </a>

  </div>

  <div class=”details”>

    <a href=”${url}”>

      <span class=”title”>${title}</span>

      <span class=”price”>${price}</span>

      {{if compare_at_price > price}}

      <span class=”price compare__price”>${compare_at_price}</span>

      {{/if}}

    </a>

  </div>

</div>

</script>

{% endraw %}

<script>

Shopify.Products.showRecentlyViewed( { howManyToShow:4 } );

</script>

<style>

/* Some styles to get you started */

.collection {

clear: both;

padding-top: 50px;

}

.collection .product {

float: left;

text-align: center;

width: 260;

padding: 0 10px;

position: relative; /* used to display absolutely positioned sale tag */

overflow: hidden;

margin-top:10px;

}

.collection .product.last {

margin-right: 0;

}

.collection .product .image {

margin-bottom: 10px;

height: 280px;

overflow: hidden;

}

.collection .product .cy {

display: block;

margin: 0 auto;

}

.collection .product .image img {

max-width: 260px;

}

.collection .product .title {

line-height: 16px;

font-size: 12px;

color: #222;

font-weight: 700;

overflow: hidden;

text-overflow: ellipsis;

display: -webkit-box;

-webkit-line-clamp: 2;

-webkit-box-orient: vertical;

}

.collection .product .price {

line-height: 16px;

font-size: 14px;

font-weight: normal;

}

  .collection .product .compare__price{

    color: red;

    text-decoration: line-through;

  }

/* new clearfix */

.clearfix:after {

visibility: hidden;

display: block;

font-size: 0;

content: ” “;

clear: both;

height: 0;

}

* html .clearfix             { zoom: 1; } /* IE6 */

*:first-child+html .clearfix { zoom: 1; } /* IE7 */

@media screen and (max-width: 789px) {

    .collection .product{

      width: 100%;

    }

    .collection .product .image img {

    max-width: 100%;

    }

  }

</style>

03

product-template中输出

    在Sections中找到product-template.liquid文件,在如下图的代码位置输出 {% include ‘recently-viewed’ %},点击保存

04

修改theme.liquid

    在Layout目录中,点击theme.liquid文件,在如下图的位置,</body>上面添加以下代码,点击保存:

<!– Begin Recently Viewed Products –>

{{ ‘//ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js’ | script_tag }}

{{ ‘jquery.products.js’ | asset_url | script_tag }}

{% if template contains ‘product’ %}

<script>

Shopify.Products.recordRecentlyViewed();

</script>

{% endif %}

<!– End Recently Viewed Products –>

做完以上四步,访问前台页面,就能看到刚刚访问的产品显示在最下方了。因为上述代码只针对Shopify免费主题,且具体图片显示尺寸需要再根据主题进行调整。如果觉得不需要那么细致,可以直接套用。
    本篇文章就分享到这里了,如果对文中所涉及内容有疑问处,可联系小编QQ : 2790641050。欢迎加入免费Shopify技术交流qq群:632205694。文中涉及到的代码,小编将会共享到qq群文件中,已经进群的伙伴可以直接进群下载。如有疑问,也可在群中与小编实时交流。

    如果觉得小编的文章对你有价值,动动你的手指,帮忙关注并转发,谢谢!

 

    参考文献:https://github.com/carolineschnapp/recently-viewed/blob/master/recently-viewed.liquid   

更多精彩推荐,请关注我们
专业的技术服务

本篇文章来源于微信公众号: shopify技术服务

发表评论

关闭菜单