I'm attempting to change item cost in truck utilizing the accompanying capability:
add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price'
);
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = 400;
}
}
It was working accurately in WooCommerce adaptation 2.6.x yet not working any longer in variant 3.0+
How might I make it work in WooCommerce Adaptation 3.0+?
Much obliged.
Solutions
Update 2021 (Dealing with scaled down truck custom thing cost)
With WooCommerce variant 3.0+ you really want:
To utilize woocommerce_before_calculate_totals snare all things considered.
To utilize WC_Cart get_cart() technique all things being equal
To utilize WC_product set_price() technique all things being equal
Here is the code:
// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 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 | optional)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_price( 40 );
}
}
Also, for smaller than expected truck (update):
// Mini cart: Display custom price
add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
if( isset( $cart_item['custom_price'] ) ) {
$args = array( 'price' => 40 );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $price_html;
}
Code goes in functions.php document of your dynamic kid subject (or dynamic topic).
This code is tried and works (actually deals with WooCommerce 5.1.x).
Note: you can expand the snare need from 20 to 1000 (or even 2000) while utilizing around barely any particular modules or others customizations.
Related:
Set truck thing cost from a secret information field custom cost in Woocommerce 3
Change truck thing costs in light of custom truck thing information in Woocommerce
Set a particular item cost restrictively on Woocommerce single item page and truck
Add a select field that will change cost in Woocommerce straightforward items