Implementing custom price adjustments in WooCommerce can be useful for store owners who may need to apply temporary price changes to any item added to the cart. This can be used when businesses may want to impose a surcharge for certain products to cover additional costs, such as handling fees or enhanced features to encourage quicker sales. In this guide, we will explore how the price override feature enables you to adjust prices for items added to the cart seamlessly.
Solution: Add a Product to Cart with Price Override in WooCommerce
The code will automatically adjust product prices by adding a custom price to the actual price when items are added to the cart.
add_filter('woocommerce_add_cart_item_data', 'ts_custom_price_adjustment', 10, 2); function ts_custom_price_adjustment($cart_item_data, $product_id) { // Add a flag to indicate price adjustment $cart_item_data['adjust_price'] = true; return $cart_item_data; } add_action('woocommerce_before_calculate_totals', 'ts_apply_price_adjustment'); function ts_apply_price_adjustment($cart) { // Check if the cart is empty or in admin if (is_admin() && !defined('DOING_AJAX')) { return; } // Loop through cart items foreach ($cart->get_cart() as $cart_item_key => $cart_item) { // Check if our custom price adjustment flag exists if (isset($cart_item['adjust_price'])) { // Adjust the price of the existing product in the cart $original_price = $cart_item['data']->get_price(); // Get the original price $additional_price = 25.00; // Set your additional price $new_price = $original_price + $additional_price; // Calculate new price $cart_item['data']->set_price($new_price); // Set the new price } } } add_action('woocommerce_product_query', 'ts_show_only_instock_products'); function ts_show_only_instock_products($query) { $meta_query = $query->get('meta_query'); $meta_query[] = array( 'key' => '_stock_status', 'compare' => '=', 'value' => 'instock' ); $query->set('meta_query', $meta_query); }
Output
When a customer visits the product page, they will see the product displayed along with its original price as shown below. Let’s add the product to the cart and see how the price override action takes place.
The original price displayed on the product page remains unchanged, but as soon as the item is added to the cart, the code modifies the price by adding the specified custom price (e.g., $25).
Want to enhance the pricing ability with lot more options? Then you can easily adjust prices by adding extra fees or giving discounts based on user roles as well. This can be achieved using a simple plugin Product Prices by User Roles for WooCommerce where you have the flexibitlity to set custom pricing for wholesalers, subscribers, or other role-specific customers.