创建一个WooCommerce兑换优惠券页面

In this article, we will explore a unique way of allowing your customers to easily redeem a product or group of products they may have paid for already perhaps at a conference or other similar event.

在本文中,我们将探索一种独特的方式,使您的客户可以轻松地赎回他们可能已经在会议或其他类似活动中支付的产品或一组产品。

Let’s talk a bit more about the concept. Say you are a store owner with a revolutionary new product and you present it to thousands of people at a conference. At the end of your speech, those customers willing to try your product can do so and pay for it ahead of time. You may even have enticed them by lowering your price to the first 500 customers.

让我们再讨论一下这个概念。 假设您是拥有革命性新产品的商店老板,并且在会议上向数千人展示了该产品。 在演讲结束时,那些愿意试用您产品的客户可以这样做并提前付款。 您甚至可以通过降低前500个客户的价格来吸引他们。

In this scenario, what you’ll do in WooCommerce is create 500 coupons, with a product discount of 100%. You could use the Smart Coupons plugin to generate these 500 coupons so that you don’t have to create them manually. Each customer who paid in advance gets a coupon code but as far as the customer knows it is just a code to redeem the products.

在这种情况下,您将在WooCommerce中创建500张优惠券,产品折扣为100%。 您可以使用Smart Coupons插件来生成这500张优惠券,这样就不必手动创建它们。 每个预先付款的客户都会得到优惠券代码,但据客户所知,这仅仅是兑换产品的代码。

创建优惠券代码 (Creating the Coupon Codes)

If you are serious enough about your offer, then you will try to make the coupon codes look random and make it hard, if not impossible for users to come up with a valid coupon code. Make sure you select which products are tied to this coupon so we can add them to the cart automatically later on. Take a look at one of the coupons I created, pay close attention to the settings:

如果您对报价很认真,那么您将尝试使优惠券代码看起来随机并且使用户难以(即使不是不可能)提供有效的优惠券代码。 确保选择与该优惠券绑定的产品,以便我们稍后可以将其自动添加到购物车中。 看一下我创建的一张优惠券,请密切注意设置:

Coupon Settings

创建WooCommerce兑换产品页面 (Creating the WooCommerce Redeem Products Page)

You can easily make a copy of your page.php and turn it into a page template so you can use it for the page we are going to be sending those customers so they can redeem their products. Name it something like page-coupon-redeem.php

您可以轻松地复制page.php并将其转换为页面模板,以便将其用于我们将要发送给这些客户的页面,以便他们可以兑换他们的产品。 将其命名为page-coupon-redeem.php

The following markup is what we’ll use to format the form displayed to the customer on that page. It is just a form with two fields, one for entering their code and the actual submit button. We are trying to keep this as simple as possible for the customer; so we are going to do everything via Ajax so there are as little page loads as possible.

以下标记是我们用来格式化在该页面上显示给客户的表单的格式。 它只是一个包含两个字段的表单,一个用于输入其代码和实际的提交按钮。 我们正在努力为客户简化这一过程; 因此我们将通过Ajax进行所有操作,以使页面加载尽可能少。

<div class="redeem-coupon">
	<form id="ajax-coupon-redeem">
		<p>
			<input type="text" name="coupon" id="coupon"/>
			<input type="submit" name="redeem-coupon" value="Redeem Offer" />
		</p>
		<p class="result"></p>
	</form><!-- #ajax-coupon-redeem -->
</div><!-- .redeem-coupon -->

When the user enters a code and hits the submit button, the value entered in the text field is sent for validation and if it happens to be valid, then the user will be redirected to the ‘Cart’ page and the products will already be there to checkout for the price of $0. If by any chance the code is incorrect, then we notify the user that something is wrong and the code entered is not valid.

当用户输入代码并点击提交按钮时,将在文本字段中输入的值用于验证,如果该值恰好是有效的,则该用户将被重定向到“购物车”页面,并且产品已经在那里签出$ 0的价格。 如果任何时候该代码不正确,那么我们会通知用户有问题,并且输入的代码无效。

构建Ajax功能 (Building the Ajax Functionality)

If you have never done Ajax in WordPress, please refer to my previous article Adding Ajax to Your WordPress Plugin for a brief introduction to how Ajax is performed in WordPress.

如果您从未在WordPress中完成过Ajax,请参阅我以前的文章将Ajax添加到WordPress插件中 ,以简要介绍如何在WordPress中执行Ajax。

Let’s begin building the Ajax functionality required for our ‘Redeem Your Products Page’ to function as expected. All the code that follows goes in your functions.php file of your theme.

让我们开始构建“兑现您的产品页面”才能正常运行所需的Ajax功能。 后面的所有代码都放在主题的functions.php文件中。

注册我们的Ajax处理程序 (Register Our Ajax Handler)

First register our Ajax call handler by hooking into the wp_ajax_$action and wp_ajax_nopriv_$action actions.

首先,通过挂接到wp_ajax_$actionwp_ajax_nopriv_$action操作来注册我们的Ajax调用处理程序。

add_action( 'wp_ajax_spyr_coupon_redeem_handler', 'spyr_coupon_redeem_handler' );
add_action( 'wp_ajax_nopriv_spyr_coupon_redeem_handler', 'spyr_coupon_redeem_handler' );

Note that the same function is handling the Ajax call for both customers whether they are logged in or not.

注意,无论两个客户是否登录,相同的功能都在处理两个客户的Ajax调用。

Next, we are going to start building our logic to account for the following possible scenarios:

接下来,我们将开始构建逻辑以解决以下可能的情况:

  • Code text field being empty

    代码文本字段为空
  • Code being invalid, meaning is not a valid coupon code

    验证码无效,表示该验证码无效
  • Successfully presenting a valid coupon

    成功出示有效的优惠券
处理优惠券逻辑 (Handling the Coupon Logic)

Now that we have our actions registered and we know what to do, we need to write the actual function which will handle our possible scenarios.

现在我们已经注册了动作并且知道该怎么做,我们需要编写实际的函数来处理可能的情况。

<?php
function spyr_coupon_redeem_handler() {

	// Get the value of the coupon code
	$code = $_REQUEST['coupon_code'];

	// Check coupon code to make sure is not empty
	if( empty( $code ) || !isset( $code ) ) {
		// Build our response
		$response = array(
			'result'    => 'error',
			'message'   => 'Code text field can not be empty.'
		);

		header( 'Content-Type: application/json' );
		echo json_encode( $response );

		// Always exit when doing ajax
		exit();
	}

	// Create an instance of WC_Coupon with our code
	$coupon = new WC_Coupon( $code );

	// Check coupon to make determine if its valid or not
	if( ! $coupon->id && ! isset( $coupon->id ) ) {
		// Build our response
		$response = array(
			'result'    => 'error',
			'message'   => 'Invalid code entered. Please try again.'
		);

		header( 'Content-Type: application/json' );
		echo json_encode( $response );

		// Always exit when doing ajax
		exit();

	} else {
		// Coupon must be valid so we must
		// populate the cart with the attached products
		foreach( $coupon->product_ids as $prod_id ) {
			WC()->cart->add_to_cart( $prod_id );
		}

		// Build our response
		$response = array(
			'result'    => 'success',
			'href'      => WC()->cart->get_cart_url()
		);

		header( 'Content-Type: application/json' );
		echo json_encode( $response );

		// Always exit when doing ajax
		exit();
	}
}

使用jQuery处理表单提交 (Handling the Form Submission with jQuery)

All that’s left to do now is build the jQuery code to submit the coupon code to WordPress for processing and handling the JSON data returned.

现在剩下要做的就是构建jQuery代码,以将优惠券代码提交给WordPress,以处理和处理返回的JSON数据。

jQuery( document ).ready( function() {
       jQuery( '#ajax-coupon-redeem input[type="submit"]').click( function( ev ) {

        // Get the coupon code
        var code = jQuery( 'input#coupon').val();

        // We are going to send this for processing
        data = {
            action: 'spyr_coupon_redeem_handler',
            coupon_code: code
        }

        // Send it over to WordPress.
        jQuery.post( woocommerce_params.ajax_url, data, function( returned_data ) {
            if( returned_data.result == 'error' ) {
                jQuery( 'p.result' ).html( returned_data.message );
            } else {
                // Hijack the browser and redirect user to cart page
                window.location.href = returned_data.href;
            }
        })

        // Prevent the form from submitting
        ev.preventDefault();
    }); 
});

最后结果 (Final Result)

The styling of the form is entirely up to you. I’ve used the default Twenty Twelve theme and WooCommerce’s dummy data and with a few CSS rules this is what I’ve got below.

表单的样式完全取决于您。 我使用了默认的“二十二十二”主题和WooCommerce的虚拟数据,并使用了一些CSS规则,这就是我在下面得到的内容。

空字段错误消息 (Empty Field Error Message)
Error Empty Field
无效的代码错误消息 (Invalid Code Error Message)
Error Invalid Code
有效的代码/购物车已填充 (Valid Code/Cart Populated)
Populated Cart

结论 (Conclusion)

Even though this scenario might not apply to every store out there, WooCommerce shines in providing us with a set of tools through their API so that we can accomplish almost anything we set our minds to. Add WordPress to the mix and you’ve got a complete eCommerce solution which is second to none.

即使这种情况可能并不适用于附近的每个商店,但WooCommerce还是会通过其API向我们提供一系列工具,从而使我们可以完成几乎所有设定的目标。 将WordPress添加到组合中,您将获得一个完整的电子商务解决方案,这是首屈一指的。

It is my hope that through this article, I’ve provided some insight of how coupons work in WooCommerce and that you’ll feel more comfortable in using it on your next project.

我希望通过本文,我能对票券在WooCommerce中的工作方式提供一些见解,并希望您在下一个项目中使用它时会感到更自在。

翻译自: https://www.sitepoint.com/creating-a-woocommerce-redeem-coupon-page/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值