Advertisement
CodeDropz

Adjust price based on the total number of files/uploads

Oct 13th, 2023
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.09 KB | None | 0 0
  1. add_filter('woocommerce_add_cart_item_data', 'custom_codedropz_change_price', 100, 2 );
  2. add_filter('woocommerce_before_calculate_totals','set_codedropz_calculate_price', 20, 1 );
  3.  
  4. function custom_codedropz_change_price( $cart_item_data, $product_id ){
  5.    
  6.     // Bail early
  7.     if( ! isset( $cart_item_data['dnd-wc-file-upload'] ) ){
  8.         return $cart_item_data;
  9.     }
  10.    
  11.     // Get total no. of files
  12.     $total_files = count( $cart_item_data['dnd-wc-file-upload'] );
  13.    
  14.     // Set Custom Price
  15.     if( $total_files > 1 ){
  16.         $product = wc_get_product($product_id);
  17.         $price = ( $product->is_on_sale() ? $product->get_sale_price() : $product->get_regular_price() );
  18.         $cart_item_data['new_price'] = ( $price * $total_files );
  19.     }
  20.    
  21.     return $cart_item_data;
  22. }
  23.  
  24. function set_codedropz_calculate_price( $cart ){
  25.    
  26.     // Bail early
  27.     if ( is_admin() && ! defined( 'DOING_AJAX' ) ){
  28.         return;
  29.     }
  30.    
  31.     // Adjust Price only if new_price is set
  32.     foreach ( $cart->get_cart() as $cart_item ) {
  33.         if( isset( $cart_item['new_price'] ) ){
  34.             $cart_item['data']->set_price( $cart_item['new_price'] );
  35.         }
  36.     }
  37. }
  38.  
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement