WooCommerce做POS的小功能

這個小function主要是讓商品id 156變成折扣,當我把它加入購物車時,就可以自己打金額折價,如果你是小型門市,1次只處理1張單,發票數又不多,可以用WooCommerce搭配速買配開發票

// 在購物車頁面為商品 156 添加價格修改欄位,並保存自定義價格到購物車和訂單
function custom_product_156_price_modification() {
    // 顯示自定義價格輸入框
    add_action('woocommerce_after_cart_item_name', function($cart_item, $cart_item_key) {
        if ($cart_item['product_id'] == 156) {
            $custom_price = isset($cart_item['custom_price']) ? $cart_item['custom_price'] : $cart_item['data']->get_price();
            echo '<input type="number" step="0.01" name="custom_price[' . $cart_item_key . ']" value="' . esc_attr($custom_price) . '" />';
        }
    }, 10, 2);

    // 保存自定義價格到購物車
    add_action('woocommerce_before_calculate_totals', function($cart) {
        if (is_admin() && !defined('DOING_AJAX')) {
            return;
        }

        foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
            if ($cart_item['product_id'] == 156 && isset($_POST['custom_price'][$cart_item_key])) {
                $custom_price = floatval($_POST['custom_price'][$cart_item_key]);
                // 更新購物車中的價格
                $cart_item['data']->set_price($custom_price);
                // 保存自定義價格到購物車項目中
                WC()->cart->cart_contents[$cart_item_key]['custom_price'] = $custom_price;
            } elseif (isset($cart_item['custom_price'])) {
                // 在沒有修改的情況下仍確保自定義價格保留
                $cart_item['data']->set_price($cart_item['custom_price']);
            }
        }
    });

    // 將自定義價格保存到訂單項目中
    add_action('woocommerce_checkout_create_order_line_item', function($item, $cart_item_key, $values, $order) {
        if (isset($values['custom_price'])) {
            $item->update_meta_data('custom_price', $values['custom_price']);
            $item->set_subtotal($values['custom_price'] * $item->get_quantity());
            $item->set_total($values['custom_price'] * $item->get_quantity());
        }
    }, 10, 4);
}

// 呼叫此函式來啟用自定義價格修改功能
add_action('init', 'custom_product_156_price_modification');
瀏覽次數:9