在 Woocommerce Bookings 中以编程方式设置基于可预订产品的成本

Set bookable product base cost programatically in Woocommerce Bookings

我正在尝试计算 WooCommerce 可预订产品的基本成本并设法使用此方法完成它:

    function modify_baseprice() {
       global $post;
       $productid = $post->ID;
       $product = new WC_Product($productid);
       $product_block_price = $product->wc_booking_block_cost;
       $product->wc_booking_cost = ($product_block_price*0.6) + 100;
       $pricing_data = update_post_meta( $productid, '_wc_booking_cost', $product->wc_booking_cost); 
       return $pricing_data; 
   }
   add_action( 'woocommerce_bookings_after_booking_base_cost', 'modify_baseprice', 10, 3 );

它确实正确计算了基本成本,但我需要刷新页面两次才能看到它出现在基本成本字段中。有什么方法可以让它在第一次保存后出现吗?

自 Woocommerce 3 发布以来,CRUD objects 已经实施。这是 WC_Product 对象的情况,也是 Woocommerce 预订插件的情况。因此,您可以使用可用的 Getters 和 setter 方法,因为属性不再可访问(在大多数情况下)。

下面的代码使用这种方式比较好(费用在产品中设置,无需刷新页面)

add_action( 'woocommerce_process_product_meta_booking', 'modify_bookable_product_base_cost', 100, 1 );
function modify_bookable_product_base_cost( $product_id ){
    // Get an instance of the WC_Product object
    $product = wc_get_product( $product_id );

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

        $product->set_cost( $new_booking_cost ); // Set the new calculated cost in the product
        $product->save(); // Save the product data
    }
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。