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

时间:2018-12-21 00:35:53

标签: php wordpress woocommerce hook-woocommerce woocommerce-bookings

我有一种情况,我需要根据工期来调整预定的总成本来更改总租金。预订持续时间是客户定义的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之类的操作来永久设置此价格,从而使折扣价显示在产品页面本身上。

1 个答案:

答案 0 :(得分:0)

我设法通过编程将价格范围添加到可预订产品中来实现这一目标:

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 );
 }
}

输入基本成本后保存产品时,它将生成基本成本并添加定价行以提供所需的结果。

enter image description here

灵感来自herehereherehere

相关问题