前言
在開發基於 WordPress 的 WooCommerce 網站時,了解訂單資料結構對於客製化功能非常重要。當訂單狀態或詳細資料更新時,能夠即時記錄這些資料有助於除錯與後續分析。本文針對 WooCommerce 訂單更新事件,說明如何使用 PHP 透過鉤子(hook)將訂單資料以 JSON 格式記錄到檔案中。
需求情境
- 監聽 WooCommerce 訂單更新事件。
- 獲取訂單的完整詳細資料。
- 將資料儲存為 JSON 格式,方便後續分析或除錯。
解決方案
利用 WooCommerce 提供的 woocommerce_order_status_changed 鉤子,在訂單狀態變更時觸發自訂函數,取得訂單資料並寫入檔案。
add_action('woocommerce_order_status_changed', 'log_order_data', 10, 4);
function log_order_data($order_id, $old_status, $new_status, $order) {
$data = [
'order_id' => $order_id,
'old_status' => $old_status,
'new_status' => $new_status,
'order_data' => $order->get_data() // 獲取訂單詳細資料
];
write_to_log_file($data, 'order_update_log.json');
}
function write_to_log_file($data, $filename = 'meta_data.json') {
$log_dir = __DIR__ . '/logs'; // 指定記錄檔存放目錄
if (!file_exists($log_dir)) {
mkdir($log_dir, 0755, true); // 如果目錄不存在,創建目錄
}
$log_file = $log_dir . '/' . $filename;
// 將資料轉換為 JSON 格式
$json_data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// 將 JSON 資料寫入文件(直接覆寫內容)
file_put_contents($log_file, $json_data);
}
程式碼解說
-
監聽訂單狀態更新事件 使用 WooCommerce 的
woocommerce_order_status_changed鉤子,當訂單狀態變更時觸發log_order_data函數。add_action('woocommerce_order_status_changed', 'log_order_data', 10, 4); -
獲取訂單詳細資料 透過
WC_Order物件的get_data()方法取得完整訂單資料,包含客戶資訊、商品清單、付款方式等。'order_data' => $order->get_data() -
記錄資料至 JSON 檔案 將資料轉換為 JSON 格式,並寫入指定的
logs目錄下的檔案中,若目錄不存在則自動建立。write_to_log_file($data, 'order_update_log.json');
範例輸出
假設訂單狀態從 processing 更新為 completed,記錄的 JSON 資料範例如下:
{
"order_id": 1234,
"old_status": "processing",
"new_status": "completed",
"order_data": {
"id": 1234,
"status": "completed",
"currency": "USD",
"total": "99.99",
"customer_id": 5678,
"billing": {
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]"
},
"line_items": [
{
"name": "T-Shirt",
"quantity": 2,
"total": "49.99"
}
]
}
}
適用場景
- 除錯需求:快速了解 WooCommerce 訂單資料結構,協助定位問題。
- 數據分析:將記錄的 JSON 資料用於訂單數據分析。
- 客製化功能開發:根據訂單詳細資料設計特定邏輯。
完整程式碼
add_action('woocommerce_order_status_changed', 'log_order_data', 10, 4);
function log_order_data($order_id, $old_status, $new_status, $order) {
$data = [
'order_id' => $order_id,
'old_status' => $old_status,
'new_status' => $new_status,
'order_data' => $order->get_data() // 獲取訂單詳細資料
];
write_to_log_file($data, 'order_update_log.json');
}
function write_to_log_file($data, $filename = 'meta_data.json') {
$log_dir = __DIR__ . '/logs'; // 指定記錄檔存放目錄
if (!file_exists($log_dir)) {
mkdir($log_dir, 0755, true); // 如果目錄不存在,創建目錄
}
$log_file = $log_dir . '/' . $filename;
// 將資料轉換為 JSON 格式
$json_data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// 將 JSON 資料寫入文件(直接覆寫內容)
file_put_contents($log_file, $json_data);
}