【问题标题】:WooCommerce Add Fee and Coupon to Programmatically Created Order [duplicate]WooCommerce 向以编程方式创建的订单添加费用和优惠券 [重复]
【发布时间】: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


    【解决方案1】:
            // Discount
            $coupon_code = 'NOFEE';
            $order->apply_coupon( $coupon_code );
    
            // Fee
            $fee_name    = 'Sign Up Fee';
            $fee_amount  = 1500;
    
            $item_fee = new WC_Order_Item_Fee();
    
            $item_fee->set_name( $fee_name );
            $item_fee->set_amount( $fee_amount );
            $item_fee->set_tax_class( '' );
            $item_fee->set_tax_status( 'taxable' ); // or 'none'
            $item_fee->set_total( $fee_amount );
    
    
            $country_code = $order->get_shipping_country();
    
            $calculate_tax_for = array(
                'country'    => $country_code,
                'state'      => '',
                'postcode'   => '',
                'city'       => ''
            );
    
            $item_fee->calculate_taxes( $calculate_tax_for );
    
            $order->add_item( $item_fee );
    

    试试这个代码

    【讨论】:

    • 收费部分工作得很好,我设法弄清楚了那部分。但是优惠券部分没有显示订单中的任何优惠券。我几乎让它与 WC_Order_Item_Coupon() 一起使用,但这仅显示订单上的优惠券,并没有实际应用折扣
    最近更新 更多