流程如下:
- 客户将产品添加到购物车。
- 客户在结帐时添加优惠券“微笑”。
- 当客户下订单时,该函数将在订单之前运行 详细信息页面加载。函数将检查“微笑”优惠券是否存在 已应用,它将重定向到它们将所在的新页面 免费提供额外的产品。如果没有,则继续 和平常一样。
我一直在引用通过 Google 搜索找到的两个与我的问题部分类似的解决方案。我单独让它们工作,但一起我似乎无法让它们正常工作。
这是我的代码:
add_action( 'woocommerce_thankyou' , 'sq_checkout_custom_redirect' );
function sq_checkout_custom_redirect($order_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$coupon_id = 'smile';
$applied_coupon = $woocommerce->cart->applied_coupons;
$url = 'https://site.mysite.org/score-you-win/';
if( $applied_coupon[0] === $coupon_id ) {
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
} else {
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
}
无论我应用什么优惠券,我都会收到“优惠券未应用”消息。并且不会发生重定向。
我引用的两个解决方案是:
Find applied coupon_id in cart
此代码成功运行:
add_action( 'woocommerce_thankyou', function ($order_id){
$order = new WC_Order( $order_id );
$coupon_id = "smile";
$url = 'https://site.mysite.org/score-you-win/';
if ($order->status != 'failed') {
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
}
});
并且运行成功:
function product_checkout_custom_content() {
global $woocommerce;
$coupon_id = 'smile';
$applied_coupon = $woocommerce->cart->applied_coupons;
if( $applied_coupon[0] === $coupon_id ) {
echo '<span style="font-size:200px; z-index:30000; color:#red !important;">We are happy you bought this product =)</span> ';
} else {
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
}
add_action( 'woocommerce_thankyou' , 'sq_checkout_custom_redirect' );
最佳答案
更新:在 woocommerce“已收到订单”页面(谢谢)中,没有更多可用的 WC_Cart
对象。相反,您需要以这种方式定位 WC_Order
对象:
add_action( 'woocommerce_thankyou', 'thankyou_custom_redirect', 20, 1 );
function thankyou_custom_redirect( $order_id ) {
// Your settings below:
$coupon_id = 'smile';
$url = 'https://site.mysite.org/score-you-win/';
// Get an instance of the WC_order object
$order = wc_get_order($order_id);
$found = false;
// Loop through the order coupon items
foreach( $order->get_items('coupon') as $coupon_item ){
if( $coupon_item->get_code() == strtolower($coupon_id) ){
$found = true; // Coupon is found
break; // We stop the loop
}
}
if( $found )
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
else
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
代码位于事件子主题(或事件主题)的 function.php 文件中。经过测试并有效。
关于javascript - 根据 WooCommerce 订单接收页面中应用的优惠券创建重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807436/