根据 WooCommerce 预订持续时间设置价格

Set prices based on WooCommerce Bookings duration

我有一个场景,我需要根据持续时间调整预订的大宗费用来更改总租赁价格。预订持续时间是客户定义的 4 天。

4 天(最短持续时间)= 基本成本 + 区块成本 8 天(最长持续时间)= 基本成本 + 区块成本 +(区块成本 *0.75)。

基于 Change price of product in WooCommerce cart and checkout 答案代码,我做了一些更改。这是我的代码:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 10, 1 );
function custom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ){
        $booking_id = $cart_item['booking']['_booking_id'];
        $booking = get_wc_booking( $booking_id );
        $base_cost  = get_post_meta( $cart_item['product_id'], '_wc_booking_cost', true );
        $block_cost = get_post_meta( $cart_item['product_id'], '_wc_booking_block_cost', true );
        if ( $booking ) {
            $duration   = $cart_item['booking']['duration'];        
            if ($duration == 8) {
                $new_price = $base_cost +$block_cost + ($block_cost * 0.75);    //Calculate the new price           
                $cart_item['data']->set_price( $new_price ); // Set the new price
            }
        }       
    }
}

这很好用,但我想知道是否有一种方法可以使用 woocommerce_bookings_pricing_fields 之类的操作永久设置它,这样折扣价就会显示在产品页面上。

我通过以编程方式向可预订产品添加价格范围来设法实现它:

add_action( 'woocommerce_process_product_meta_booking', 'modify_product_costs', 100, 1 );

function modify_product_costs( $product_id ){
  $product = wc_get_product( $product_id );

  // We check that we have a block cost before
  if ( $product->get_block_cost() > 0 ){
    // Set base cost
    $new_booking_cost = ( $product->get_block_cost() * 0.5 ) + 100;

    $product->set_cost( $new_booking_cost ); 
    $product->save(); // Save the product data

    //Adjust cost for 8 days
    $pricing = array(
    array(
    'type' => 'blocks',
    'cost' => 0.875,
    'modifier' => 'times',
    'base_cost' => $new_booking_cost,
    'base_modifier' => 'equals',
    'from' => 2,
    'to' => 2
    )
    );

    update_post_meta( $product_id, '_wc_booking_pricing', $pricing );
 }
}

在输入块成本后保存产品时,它会生成基本成本并添加一条定价线以提供所需的结果。

灵感来自, , here and