如何在 WooCommerce 中检查哪个优惠券适用于哪个产品? [英] How to check which coupon is applied to which product in WooCommerce?

查看:67
本文介绍了如何在 WooCommerce 中检查哪个优惠券适用于哪个产品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们可以为订单中的每个产品应用不同的优惠券,有什么方法可以知道哪个优惠券适用于哪个产品?我使用了 $order->get_used_coupons() 函数,但它只返回使用过的优惠券代码.

Since we can apply different coupons to each product in an order, Is there any method to know which coupon is applied to which product? I've used $order->get_used_coupons() function but it just returns the used coupon codes only.

请帮忙解决.谢谢.

推荐答案

2016 年 6 月为 Woocommerce 2.5.x 制作的示例(不适用于 Woocommerce 3+)

Example made for Woocommerce 2.5.x on June 2016 (Will not work in Woocommerce 3+)

此示例基于编译搜索:

function wc_my_order_coupons( $order_id ) {
    $order = new WC_Order( $order_id );

    // checking if order has some used coupons
    if( sizeof($order->get_used_coupons()) > 0 ) {
        foreach( $order->get_used_coupons() as $coupon_code ) {

            // Retrieving the coupon ID
            $post_obj = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
            $coupon_id = $post_obj->ID;

            // here is a list of most all data that you can use for a coupon
            $cp_discount_type = get_post_meta( $coupon_id, 'discount_type', true );
            $cp_amount = get_post_meta( $coupon_id, 'coupon_amount', true );
            $cp_indiv_use = get_post_meta( $coupon_id, 'individual_use', true );
            $cp_products = get_post_meta( $coupon_id, 'product_ids' ); 
            $cp_excl_products = get_post_meta( $coupon_id, 'exclude_product_ids' );
            $cp_usage_limit = get_post_meta( $coupon_id, 'usage_limit', true );
            $cp_expiry_date = get_post_meta( $coupon_id, 'expiry_date', true );
            $cp_apply_before_tax = get_post_meta( $coupon_id, 'apply_before_tax', true );
            $cp_free_shipping = get_post_meta( $coupon_id, 'free_shipping', true ); 

            // Getting the products in this order_id
            $items = $order->get_items();
            foreach ($items as $key => $item) {
                $product_name = $item['name'];
                $product_id = $item['product_id'];

                // Example: we use product_ids authorized in the coupon $cp_products
                if (in_array($product_id, $cp_products)) {
                    echo $product_name . 'uses the coupon: ' . $coupon->code . '<br>';
                }
            }
        }
    }
}

参考资料:

这篇关于如何在 WooCommerce 中检查哪个优惠券适用于哪个产品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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