Вот моя текущая функция: < /p>
Код: Выделить всё
function create_order_with_pending_status_and_customer($email, $billing_link, $product_id, $quantity = 1, $coupon_code = "")
{
if (!class_exists('WC_Order')) {
return 'Error: WooCommerce not loaded.';
}
// Start session if not already started
if (!session_id()) {
session_start();
}
// Check if an order ID exists in the session
if (isset($_SESSION['order_id'])) {
$order_id = $_SESSION['order_id'];
$order = wc_get_order($order_id);
// Validate the order
if ($order && $order->get_status() === 'pending') {
foreach ($order->get_items() as $item) {
if ($item->get_product_id() == $product_id) {
return $order_id; // Return existing order ID if product is already in the order
}
}
}
}
// Get product details
$product = wc_get_product($product_id);
if (!$product || !$product->get_price()) {
return 'Error: Product not found or invalid price.';
}
// Get or create customer
$user = get_user_by('email', $email);
if ($user) {
$customer_id = $user->ID;
} else {
$customer_id = wc_create_new_customer($email, '', wp_generate_password());
if (is_wp_error($customer_id)) {
return 'Error creating customer: ' . $customer_id->get_error_message();
}
}
// Calculate total price
$total_price = $product->get_price() * $quantity;
// Create a new WooCommerce order
$order = wc_create_order();
// Add product to the order
$order->add_product($product, $quantity);
// Set customer details
$order->set_customer_id($customer_id);
// Set billing details
$billing_address = [
'email' => $email,
];
$order->set_address($billing_address, 'billing');
// Add custom meta data
$order->update_meta_data('billing_link', $billing_link);
// Apply coupon code (if provided)
if (!empty($coupon_code)) {
$order->apply_coupon($coupon_code);
}
$order->calculate_totals();
// Set order status
$order->set_status('pending');
// Set order total
$order->set_total($total_price);
// Save the order
$order->save();
// Store the order ID in the session
$_SESSION['order_id'] = $order->get_id();
return $order->get_id(); // Return the created Order ID
}
< /code>
После применения купона общая цена остается неизменной в сводке заказа. Тем не менее, цена продукта показывает скидку. Например:
[list]
[*] Цена продукта: 24,99 долл. США
Но общая сумма заказа по -прежнему показывает $ 24,99 вместо $ 16,24 .
[/list]
Любое решение ценится!
Подробнее здесь: https://stackoverflow.com/questions/793 ... it-program