В Woocommerce я пытаюсь найти способ применить 10% скидку на весь заказ клиента, если вес в тележке превышает 100 фунтов. Я часть пути к достижению этого. Для следующего шага я ищу способ программно применить код купона через action/hook через функции. Php.
Кажется, что я могу использовать функцию woocommerce_ajax_apply_coupon для этого (http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html), но я не уверен, как ее использовать.
Пока я изменил cart.php, чтобы получить общий вес всех продуктов в корзине, я создал купон, который применяет скидку (если вводится вручную), и я добавил код к функциям. php, чтобы проверить вес и отобразить сообщение пользователю.
EDIT: Частичный код удален, код завершен в приведенном ниже решении.
Спасибо за руководство Freney. Здесь результат рабочего конца, который успешно применяет скидочный купон при выполнении условия, а также удаляет его, когда он больше не выполняется:
/* Mod: 10% Discount for weight greater than 100 lbs
Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $total_weight of cart:
global $total_weight;
$total_weight = $woocommerce->cart->cart_contents_weight;
*/
add_action('woocommerce_before_cart_table', 'discount_when_weight_greater_than_100');
function discount_when_weight_greater_than_100( ) {
global $woocommerce;
global $total_weight;
if( $total_weight > 100 ) {
$coupon_code = '999';
if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
$woocommerce->show_messages();
}
echo '<div class="woocommerce_message"><strong>Your order is over 100 lbs so a 10% Discount has been Applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
}
}
/* Mod: Remove 10% Discount for weight less than or equal to 100 lbs */
add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less');
function remove_coupon_if_weight_100_or_less( ) {
global $woocommerce;
global $total_weight;
if( $total_weight <= 100 ) {
$coupon_code = '999';
$woocommerce->cart->get_applied_coupons();
if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
$woocommerce->show_messages();
}
$woocommerce->cart->calculate_totals();
}
}