Home > Backend Development > PHP Tutorial > How to Programmatically Change Product Prices in a WooCommerce Cart?

How to Programmatically Change Product Prices in a WooCommerce Cart?

DDD
Release: 2024-11-29 15:42:14
Original
317 people have browsed it

How to Programmatically Change Product Prices in a WooCommerce Cart?

Change Product Prices in Cart for WooCommerce 3

To modify product prices in the cart, you can use the following code:

// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

// Handle mini cart custom item price (Optional)
if ( ! is_admin() || defined( 'DOING_AJAX' ) ) :
    add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
endif;

// Respective Functions
function add_custom_price( $cart ) {
   // Required for WC 3.0+
   if ( is_admin() && ! defined( 'DOING_AJAX' ) )
       return;

   // Avoid hook repetition
   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 );
   }
}

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;
}
Copy after login

Notes:

  • Use the woocommerce_before_calculate_totals hook instead of woocommerce_before_shipping_calculator.
  • Use the WC_Cart::get_cart() method to obtain the cart items.
  • Use the WC_Product::set_price() method to set the price for each cart item.

Additional Information:

  • The add_custom_price() function should be placed in the functions.php file of your WordPress theme.
  • To make it compatible with WooCommerce 5.1.x and later, increase the hook priority in the add_custom_price() function to 1000 or even 2000 if necessary.
  • If using plugins or customizations that may conflict with the price calculations, increase the hook priority as well.

The above is the detailed content of How to Programmatically Change Product Prices in a WooCommerce Cart?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template