WooCommerce - Adding a custom price to each product in cart

后端 未结 1 1169
感动是毒
感动是毒 2020-12-21 11:16

I would like to update the price of products adding a custom price in cart using this simple piece of code update_post_meta( $product->id, \'_regular_price\', $fram

相关标签:
1条回答
  • 2020-12-21 11:36

    Update: For WooCommerce 3.0+ Change cart item prices in WooCommerce version 3.0

    You can use woocommerce_before_calculate_totals hook to customize your cart items prices.

    You can define $framed_price variables as global in your function, this way.

    This is the code:

    // getting your additional price outside the function (making any conditional calculations) 
    $framed_price = 20;
    
    add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10 );
    function add_custom_total_price( $cart_object ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        global $framed_price;
    
        foreach ( $cart_object->get_cart() as $key => $value ) {
            $value['data']->price += $framed_price;
        }
    }
    

    Or get your custom price inside the hooked function (optionally, depending on how you get your custom price):

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_total_price', 10 );
    function add_custom_total_price( $cart_object ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $framed_price = 20;
    
        foreach ( $cart_object->get_cart() as $key => $value ) {
            $value['data']->price += $framed_price;
        }
    }
    

    This code is tested and working.

    Naturally this code goes on function.php file of your active child theme (or theme) or in any plugin file.

    Reference: WooCommerce Cart - Dynamic Price variable pass into custom price hook

    0 讨论(0)
提交回复
热议问题