如何在WooCommerce中检查应用于哪个产品的优惠券?

3

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

请帮忙提供解决方案。 谢谢。

1个回答

4

这个例子是基于 Woocommerce 2.5.x 在2016年6月制作的(在 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>';
                }
            }
        }
    }
}

参考资料:


感谢@LoicTheAztec提供的代码片段,非常感激。抱歉回复有些晚了。我已经使用了这段代码,但如果一个优惠券可以应用于两个或更多产品,会出现问题,我是正确的吗? - Mûhámmàd Yäsår K
@MûhámmàdYäsårK 是的,那可能是正确的。但是肯定可以解决,因为一切都取决于你的时间和努力。感谢您的支持 :) … 这段代码片段是否有效? - LoicTheAztec
get_used_coupons() 返回一个优惠券代码的数组,它不是上面代码片段所处理的对象。 - Andrew Schultz
@AndrewSchultz 这是在Woocommerce 2.5版本时,所以自从Woocommerce 3版本后已经有所改变...我会进行更新。 - LoicTheAztec
WooCommerce的2.6.13版本返回一个字符串数组,因此它们必须在2.5和2.613版本之间进行了更改。 - Andrew Schultz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接