針對日期欄位 shippind_date_note
這個功能對我來說,可以說是很夢幻的功能,接觸電商10幾年來架站,很久就在想限制期的功能如何達成,ChatGPT真的很能實現願望 XD
WooCommerce透過function語法去控制 date 欄位 (shippind_date_note ; 可自訂義)
- 只能選 今天+2天
- 禮拜天不能選
- 禮拜五及六不能選禮拜一
- 特定時段不能選 [2024/09/17~2024/09/19及2024/09/25~2024/09/26]
- 同一個時間只能累積5張單
add_action('wp_footer', 'disable_weekend_and_past_dates_script'); function disable_weekend_and_past_dates_script() { ?> <script> document.addEventListener("DOMContentLoaded", function () { const dateField = document.getElementById('shippind_date_note'); // 錯誤訊息顯示的區域 const errorMessage = document.createElement('span'); errorMessage.style.color = 'red'; errorMessage.style.display = 'none'; dateField.parentNode.insertBefore(errorMessage, dateField.nextSibling); // 設定最小可選日期為今天加兩天 const today = new Date(); const minDate = new Date(today.setDate(today.getDate() + 2)).toISOString().split('T')[0]; dateField.setAttribute('min', minDate); // 定義無法選擇的日期區間 const disabledRanges = [ {start: new Date('2024-09-17'), end: new Date('2024-09-19')}, {start: new Date('2024-09-25'), end: new Date('2024-09-26')} ]; // 判斷日期是否在禁用區間內 function isDateInDisabledRange(date) { return disabledRanges.some(range => date >= range.start && date <= range.end); } function showError(message) { errorMessage.textContent = message; errorMessage.style.display = 'block'; } function clearError() { errorMessage.textContent = ''; errorMessage.style.display = 'none'; } // 模擬儲存訂單日期的數據庫 (可以替換為實際的 API 調用) const orderCountMap = JSON.parse(localStorage.getItem('orderCountMap')) || {}; function updateOrderCount(date) { // 如果該日期不存在,初始化為 0 if (!orderCountMap[date]) { orderCountMap[date] = 0; } return orderCountMap[date]; } dateField.addEventListener('input', function () { clearError(); // 先清除舊的錯誤訊息 const selectedDate = this.value; const selectedDateObj = new Date(selectedDate); const day = selectedDateObj.getDay(); // 取得星期幾,0 是星期日,6 是星期六 // 無法選擇週日 if (day === 0) { showError("無法選擇週日,請選擇其他日期。"); this.value = ''; return; } // 如果選擇的日期在今天+2天之前,則清空日期欄位 if (selectedDateObj < new Date(minDate)) { showError("您只能選擇今天加兩天之後的日期。"); this.value = ''; return; } // 禁用指定日期區間 if (isDateInDisabledRange(selectedDateObj)) { showError("選擇的日期不可用,請選擇其他日期。"); this.value = ''; return; } // 如果是禮拜五或禮拜六,無法選擇禮拜一 const currentDay = new Date().getDay(); // 取得今天是星期幾 if ((currentDay === 5 || currentDay === 6) && day === 1) { // 如果今天是禮拜五(5)或禮拜六(6),選擇的是禮拜一(1) showError("禮拜五或禮拜六無法選擇禮拜一,請選擇其他日期。"); this.value = ''; return; } // 監控選擇的日期,如果超過 5 個,禁止選擇 const currentOrderCount = updateOrderCount(selectedDate); if (currentOrderCount >= 5) { showError("該日期已達到最多可選次數,請選擇其他日期。"); this.value = ''; } else { // 更新訂單次數 orderCountMap[selectedDate] = currentOrderCount + 1; localStorage.setItem('orderCountMap', JSON.stringify(orderCountMap)); } }); }); </script> <?php }