【问题标题】:How to add coupon to WooCommerce product page [closed]如何将优惠券添加到 WooCommerce 产品页面 [关闭]
【发布时间】:2019-02-17 03:06:03
【问题描述】:

我正在使用 WordPress (4.9.8) 和 WooCommerce (3.4.5),我想在单个产品页面中添加优惠券字段。我一直在查看所有 Woocommerce 模板,但找不到将 Woocommerce 优惠券字段添加到产品页面的方法。

有什么想法吗?

我不想为此使用插件。

【问题讨论】:

    标签: php wordpress woocommerce field coupon


    【解决方案1】:

    以下代码将在添加到购物车按钮之前在单个产品页面中为优惠券添加自定义文本输入字段。

    如果在商品添加到购物车时在该字段中输入优惠券代码,优惠券代码将应用于购物车。

    代码:

    // 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;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    如果你想让优惠券字段 ajax 支持,这个问题的堆栈溢出会更加复杂和宽泛,无需提供任何代码。

    【讨论】:

    • 非常感谢。太棒了。再次感谢您。
    猜你喜欢
    • 2013-11-28
    • 2017-12-29
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多