在WooCommerce商品頁面增加留言討論功能

WooCommerce商品頁面可透過修改模板新增留言功能,無需安裝外掛。只要複製single-product-reviews.php到佈景主題資料夾,並調整程式碼即可。但評價和留言無法並存,需視需求選擇。

在WooCommerce預設功能中,每個商品頁面都有評價功能(Review),但是顧客只能夠一次性留言,不能回覆及討論。如果你想增加留言討論(Comment)或是Q&A功能,其中一個方法是安裝外掛,像是WooDiscuz。但還有另外一個方法,只要修改WooCommerce預設的模板(Template,或稱為套版)就可以完成,不需要額外任何安裝外掛。

事實上,WooCommerce的評價功能和WordPress的留言是完全一樣的機制,只是透過不一樣的樣式呈現而已。因此,我們要做的事情是覆蓋WooCommerce原本的模板。

步驟一、 複製模板到佈景主題資料夾

到外掛資料夾中,複製single-product-reviews.php這個檔案,路徑如下:

/wp-content/plugins/woocommerce/templates/single-product-reviews.php

然後貼到你的佈景主題資料夾下:

/wp-content/themes/[佈景名稱]/woocommerce

這個方式可以覆寫WooCommerce預設的模板,卻又不會直接修改原始檔,算是WooCommerce客製化的標準作法。

步驟二、調整程式碼

只要增加以下這一行程式碼,就可以在商品頁面呈現WordPress的留言區樣式,其他原始的code就可以直接刪除。

require get_template_directory() . ‘/comments.php’;

新的single-product-reviews.php會長這樣:

<?php
/**
 * Display single product reviews (comments)
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product-reviews.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates
 * @version 4.3.0
 */
defined( 'ABSPATH' ) || exit;
global $product;
if ( ! comments_open() ) {
	return;
}
require get_template_directory() . '/comments.php';
?>

缺點

這個方法超簡單,而且超實用,但它也有缺點。因於商品評價和留言是完全一樣的機制,代表兩者不能並存,有評價就沒有留言,有留言就沒有評價,就看你的需求為何。

🚀 以每年 5 美元解鎖無廣告體驗

✓ 14 天免費試用 ✓ 隨時取消

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *