【发布时间】:2025-12-27 08:10:11
【问题描述】:
我正在开发一个为指定用户创建订单/订阅的函数。这部分效果很好,但我无法在订单中添加费用或优惠券。我尝试在订单对象上使用 add_fee() 和 add_discount() 。 add_discount() 函数只是破坏了我的函数,所以我假设这个函数不能用于订单对象。而 add_fee() 只是添加了一个名为“fee”的费用,没有任何价值。
那么如何向以编程方式创建的订单添加费用和优惠券?
这是我的功能:
function give_user_subscription($companyId, $productId, $companyName) {
// get the primary contact ID for the company
$primaryUser = get_users( array(
'fields' => array('ID'),
'meta_query' =>
array(
'relation' => 'AND',
array(
'key' => 'company_id',
'value' => $companyId,
'compare' => '='
),
array(
'key' => 'primary_contact',
'value' => 1,
'compare' => '='
)
),
) );
$userId = $primaryUser[0]->ID;
$user = get_user_by('ID', $userId);
$address = array(
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->user_email,
'phone' => get_user_meta($userId, 'mobile', true),
'address_1' => get_user_meta($userId, 'address_line_1', true),
'address_2' => get_user_meta($userId, 'address_line_2', true),
'city' => get_user_meta($userId, 'town', true),
'postcode' => get_user_meta($userId, 'postcode', true),
'country' => get_user_meta($userId, 'country', true),
'company' => $companyName
);
// order object
$order = wc_create_order(array(
'customer_id' => $userId
));
$order->set_address($address, 'billing'); // Set customer billing adress
$order->add_fee( 'Sign Up Fee', 1500 );
$order->add_discount('NOFEE');
$product = wc_get_product($productId);
$order->add_product($product, 1); // Add an order line item
// Set payment gateway
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method( $payment_gateways['bacs'] );
$order->calculate_totals(); // Update order taxes and totals
$order->update_status('completed', 'Manual approval ', true); // Set order status and save
$subscription = wcs_create_subscription(array(
'status' => 'pending',
'order_id' => $order->get_id(),
'customer_id' => $userId,
'billing_period' => WC_Subscriptions_Product::get_period($product),
'billing_interval' => WC_Subscriptions_Product::get_interval($product),
));
// if( is_wp_error( $subscription ) ){
// echo $subscription->get_error_message();
// // return false;
// }
$start_date = gmdate('Y-m-d H:i:s');
// Add product to subscription
$subscription->add_product($product, 1);
$dates = array(
'trial_end' => WC_Subscriptions_Product::get_trial_expiration_date( $product, $start_date ),
'next_payment' => WC_Subscriptions_Product::get_first_renewal_payment_date( $product, $start_date ),
'end' => WC_Subscriptions_Product::get_expiration_date( $product, $start_date ),
);
$subscription->update_dates($dates);
$subscription->set_address($address, 'billing');
$subscription->calculate_totals();
// Update order status with custom note
$note = ! empty( $note ) ? $note : __('Manually added order and subscription.');
$order->update_status('completed', $note, true);
// Update subscription status
$subscription->update_status('active', $note, true);
}
【问题讨论】:
标签: php wordpress woocommerce woocommerce-subscriptions