在Woocommerce中,我试图找到一种方法,如果购物车中的重量超过100磅,则可以对整个客户的订单应用10%的折扣.我是实现这一目标的一部分.对于下一步,我正在寻找一种通过actions.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 …
Run Code Online (Sandbox Code Playgroud)