Change cart item prices in Woocommerce 3

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 19:06:45

Update (September 2018)

With WooCommerce version 3.0+ you need:

Here is the code:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 20, 1);
function add_custom_price( $cart ) {

    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        $item['data']->set_price( 40 );
    }
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Note: you can increase the hook priority from 20 to 1000 (or even 2000) when using some few specific plugins or others customizations.

Related:

With WooCommerce version 3.2.6, @LoicTheAztec's answer works for me if I increase the priority to 1000.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

I tried priority values of 10,99 and 999 but the price and total in my cart did not change (even though I was able to confirm with get_price() that set_price() had actually set the price of the item.

I have a custom hook that adds a fee to my cart and I'm using a 3rd party plugin that adds product attributes. I suspect that these WooCommerce "add-ons" introduce delays that require me to delay my custom action.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!