如何将优惠券添加到WooCommerce产品页面 [英] How to add coupon to WooCommerce product page

查看:84
本文介绍了如何将优惠券添加到WooCommerce产品页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将WordPress(4.9.8)与WooCommerce(3.4.5)结合使用,我想在单个产品页面中添加优惠券字段.我一直在查看所有Woocommerce模板,但是找不到将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.

有什么想法吗?

我不想为此使用插件.

推荐答案

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

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

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

代码:

// 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文件中.经过测试,可以正常工作.

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

如果您希望使用优惠券字段 ajax ,那么它就更复杂了,而且对于该问题的堆栈溢出来说也太宽泛了,而没有提供任何代码.

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.

这篇关于如何将优惠券添加到WooCommerce产品页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆