Woocommerce では、カート内の重量が 100 ポンドを超える場合、顧客の注文全体に 10% の割引を適用する方法を見つけようとしています。私はこれを達成する途中です。次のステップとして、functions.php のアクション/フックを介してプログラムでクーポン コードを適用する方法を探しています。
関数 woocommerce_ajax_apply_coupon を使用してこれを行うことができるようです ( http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html )が、使用方法がわかりません。
これまでのところ、カート内のすべての製品の合計重量を取得するように cart.php を変更し、割引を適用するクーポンを作成し (手動で入力した場合)、チェックするコードを functions.php に追加しました。重量を表示し、ユーザーにメッセージを表示します。
編集:部分的なコードが削除され、完成したコードが以下のソリューションに含まれています。
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();
}
}