If you’re selling things on your WordPress site using WooCommerce, you may need to adjust the price of a product in your basket. Here’s how to go about it.
Price overriding in the cart is a useful feature if we want to increase or decrease the price of a product by a fixed amount. This can be accomplished by creating price rules in addition to a static price. From the standpoint of a developer, this is a very useful code snippet.
In this article, I’ll teach you how to use the WooCommerce action hook and cart object to alter the pricing of goods that are already in the cart before calculating totals.
WooCommerce Set Custom Product Price When Adding To Cart – In this article, we’ll see how we can override the price of the product when adding the product to the cart.
With WooCommerce version 3.0+ you need:
- To use woocommerce_before_calculate_totals hook instead.
- To use WC_Cart get_cart() method instead
- To use WC_product set_price() method instead
The Code goes in the function.php file of your active child theme (or theme) or also in any plugin file.
Here is the code:
“Changes all prices in single hook“
<?php
add_action( 'woocommerce_before_calculate_totals', 'cxc_woocommerce_add_custom_price', 20, 1 );
function cxc_woocommerce_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 );
}
}
?>
“Change price in specific product category woocommerce“
<?php
add_action( 'woocommerce_before_calculate_totals', 'cxc_woocommerce_change_price_specific_category', 99, 1 );
function cxc_woocommerce_change_price_specific_category( $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;
}
$product_cart_id = 21; // Product ID
// Loop through cart items
foreach ( $cart->get_cart() as $item ) {
if( isset( $item['product_id'] ) ){
$product_id = $item['product_id'];
$product = wc_get_product( $product_id );
$cat_ids = $product->get_category_ids();
if( $cat_ids && in_array( $product_cart_id, $cat_ids ) ){
$item['data']->set_price( 10 );
}
}
}
}
?>