dousou2911 2018-09-12 12:55
浏览 333
已采纳

如何在WooCommerce产品页面添加优惠券

I am using WordPress (4.9.8) with WooCommerce (3.4.5) and I would like to add a coupon field in single product pages. I've been looking at all Woocommerce templates, but I cannot find a way to add the Woocommerce coupon field onto the product page.

Any ideas?

I don't want to use a plugin for this.

  • 写回答

1条回答 默认 最新

  • dtx3006 2018-09-12 14:04
    关注

    The following code will add a custom text input field for coupon in single product pages before add to cart button.

    enter image description here

    If a coupon code is inputed in that field when the product will be added to cart, the coupon code will be applied to cart.

    The code:

    // Add a text input field inside the add to cart form
    add_action('woocommerce_single_product_summary','add_custom_text_field_single_product', 2 );
    function add_custom_text_field_single_product(){
        global $product;
    
        if( $product->is_type('variable') ){
            add_action('woocommerce_before_single_variation','custom_product_text_input_field', 30 );
        } else {
            add_action('woocommerce_before_add_to_cart_button','custom_product_text_input_field', 30 );
        }
    }
    
    function custom_product_text_input_field(){
        echo '<div class="hidden-field">
        <p class="form-row product-coupon form-row-wide" id="product-coupon_field" data-priority="">
            <label for="product-coupon" class="">' . __("Do you have a coupon code?") . '</label>
            <span class="woocommerce-input-wrapper">
                <input type="text" class="input-text " name="product-coupon" id="product-coupon" placeholder="'.__("Coupon code").'" value="">
            </span>
        </p></div>';
    }
    
    // Apply the coupon code from product custom text imput field
    add_filter('woocommerce_add_cart_item_data', 'coupon_code_product_add_to_cart', 20, 3);
    function coupon_code_product_add_to_cart($cart_item_data, $product_id, $variation_id) {
        if (isset($_POST['product-coupon']) && ! empty($_POST['product-coupon'])) {
            WC()->cart->apply_coupon( sanitize_title( $_POST['product-coupon'] ) );
        }
        return $cart_item_data;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    If you want to have tha coupon field ajax powered, It's just more complicate and too broad for stack overflow on this question, without providing any code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真