Woocommerce modifica del prezzo in base ai giorni a fine mese

  • Categoria dell'articolo:Tech / wordpress
Al momento stai visualizzando Woocommerce modifica del prezzo in base ai giorni a fine mese

modify a woocommerce product price depending of the days left to the end of month:

// Hook into the "woocommerce_before_calculate_totals" action
add_action('woocommerce_before_calculate_totals', 'iabaduu_modify_product_prices', 10, 1);

function iabaduu_modify_product_prices($cart) {
  if (is_admin() && !defined('DOING_AJAX')) {
    return;
  }

  // Create a DateTime object for the current date and time
  $now = new DateTime();

  // Create a DateTime object for the first day of the next month
  $nextMonth = new DateTime();
  $nextMonth->modify('first day of next month');

  // Calculate the difference between the two dates
  $diff = $now->diff($nextMonth);

  // Format the difference as a string
  $daysUntilNextMonth = $diff->format('%a');

  // Loop through the cart items
  foreach($cart->get_cart() as $cart_item) {
					// Find the product by ID
					if ( 544 === $cart_item['product_id'] ) {
							    // Get the product object
							    $product = $cart_item['data'];

							    // Calculate the new price
							    $newPrice = $product->get_price() * $daysUntilNextMonth;

							    // Update the product price
							    $product->set_price($newPrice);
  				}
			}
}

This code will loop through all the items in the cart and modify their prices based on the number of days left until the end of the month. The new price is calculated by multiplying the current price by a discount factor, which is determined by the number of days remaining in the month.