Photo by Shubham Dhage on Unsplash
WordPress 的 WooCommerce 購物車快取的問題,現在的快取外掛,多數可以處理購物車 (cart)、結帳頁 (checkout)、帳號登陸頁 (account) 快取的問題,只要這三個部分不做快取,購物功能是不會有影響。
如果是用主機端直接做 Nginx FastCGI Cache,因為是 Page Cache 方式,所以在 WooCommerce 部分,也會一起被快取,會發生明明把商品放進購物車內了,查看購物車後,還是顯示 0 物品。
在 EasyEngine 或 Webinoly 中,Nginx FastCGI Cache 會加入 woocommerce_items_in_cart 參數,當使用者選購商品放入購物車後,快取模式會取消。
當使用者結帳完畢後,才會回到網站的快取模式。
這是一個最安全的做法,但會有一個小瑕疵:
當使用者的購物車有一樣商品,然後繼續購物,這時瀏覽網站時,已經沒有快取效果,直接與資料庫的連結,屬於動態網頁了;如果線上人數很多,購物車裡都有商品,這時的主機負載會變得很大。
所以,希望是當使用者購物車有商品時,只有購物車、結賬頁、登陸頁不要有快取,其他頁面 (商品頁) 還是有快取的狀態,使用者繼續挑選商品時,頁面還是有快取的狀態。
修改 FastCGI Cache 快取
打開 wpfc.conf 文件 (適用於 EasyEngine 與 Webinoly)
# Don't use the cache for logged in users or recent commenter or customer with items in cart
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|woocommerce_items_in_cart") {
set $skip_cache 1;
}
修改為
# Don't use the cache for logged in users or recent commenter or customer with items in cart
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
set $skip_cache 1;
}
下方再加入以下配置:(關閉購物車、結賬頁、登陸頁快取功能)
# Don't cache shopping basket, checkout or account pages
if ($request_uri ~* "/cart/*$|/checkout/*$|/my-account/*$") {
set $skip_cache 1;
}
檢查一次 conf 是否正確,重啟 nginx
nginx -t && service nginx restart
可以開啟 Chrome F12 檢查頁面是否有正確的快取

結語:
我個人的心得,WooCommerce 購物車的快取機制,是不好做的,從商品放入購物車後,很多情形下是沒有快取,即使商品頁面繼續維持快取狀態,當使用者使用「篩選」方式後,又會變成沒有快取的狀態,這時的資料庫的負載是蠻大的,還好 FastCGI Cache 還可以加入 redis 或 memcached 來降低一點負載。
有人問我 WP Rocket 可不可以也加入 redis 或 memcached 來做資料庫快取,這個我沒試過效果如何,去年就有使用者建議 WP Rocket 加入 memcached 的選項,好像沒有被官方採納,連結如下:
https://trello.com/c/rH5GtO21
WP Rocket 文檔,加入 Memcached 外掛
https://docs.wp-rocket.me/article/116-does-wp-rocket-support-memcached/
參考資料:
WooCommerce Window Shopping Caching Technique
https://easyengine.io/tutorials/wordpress/woocommerce-window-shopping-caching-technique/
Webinoly 安裝 VPS 教學系列文章:
1. Webinoly 快速安裝 WordPress 教學
https://yungke.me/webinoly-easy-install-wordpress/
2. Webinoly 安裝後如何更改 PHP 版本
https://yungke.me/webinoly-change-php-version/
3. FastCGI Cache 快取 WooCommerce 的問題
4. Webinoly 的 Zend Opcache 性能優化
https://yungke.me/webinoly-zendopcache-optimization/
5. Webinoly 的 Memcached 性能優化
https://yungke.me/webinoly-memcached-optimization/
6. 阻擋 MJ12bot 惡意蜘蛛訪問
https://yungke.me/blocked-mj12bot-spider-access/
7. Webinoly 安裝 VPS 教學
https://yungke.me/webinoly-install-vps/
8. Webinoly 安裝 VPS 教學 – 進階版
https://yungke.me/webinoly-install-vps-advanced/

發佈留言