dongqian0763 2018-11-15 19:35
浏览 37
已采纳

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

I am trying to calculate the Base cost of a WooCommerce bookable product and managed to get it done using this:

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

It does calculate the Base cost correctly but I need to refresh the page twice to see it appearing on the Base cost field. Is there a way that I can get it to appear after the first save?

enter image description here

  • 写回答

1条回答 默认 最新

  • dqc42632 2018-11-15 20:15
    关注

    Since Woocommerce 3 release, CRUD objects have been implemented. It's the case of WC_Product object and also for Woocommerce Bookings plugin. So you can use available Getters and setters methods as properties are not anymore accessible (in most cases).

    The following code use this better way (The cost is set in the product without any need of refreshing the page):

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

    Code goes in function.php file of your active child theme (active theme). Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号