【问题标题】:Get used coupon codes and related discount amounts from WooCommerce orders从 WooCommerce 订单中获取使用过的优惠券代码和相关折扣金额
【发布时间】:2021-05-27 20:04:34
【问题描述】:

我需要在自定义插件中插入代码,以获取我在设置中输入的折扣代码的名称、使用代码获得的折扣以及总数。

根据Get coupon data from WooCommerce orders答案代码,我插入了以下代码:

$order = wc_get_order( $order_id );

// GET THE ORDER COUPON ITEMS
$order_items = $order->get_items('coupon');

// print_r($order_items); // For testing

// LOOP THROUGH ORDER COUPON ITEMS
foreach( $order_items as $item_id => $item ){

    // Retrieving the coupon ID reference
    $coupon_post_obj = get_page_by_title( $item->get_name(), OBJECT, 'shop_coupon' );
    $coupon_id = $coupon_post_obj->ID;

    // Get an instance of WC_Coupon object (necessary to use WC_Coupon methods)
    $coupon = new WC_Coupon($coupon_id);

    ## Filtering with your coupon custom types
    if( $coupon->is_type( 'fixed' ) || $coupon->is_type( 'percent' ) || $coupon->is_type( 'fixed_product' ) ){

        // Get the Coupon discount amounts in the order
        $order_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
        $order_discount_tax_amount = wc_get_order_item_meta( $item_id, 'discount_amount_tax', true );

        ## Or get the coupon amount object
        $coupons_amount = $coupons->get_amount();
    }

}       
$confirmation = str_ireplace("{order_items}", $order_items, $confirmation);

但是当我做回声时,它带给我的唯一信息是“数组”这个词。

我做错了什么?有什么帮助吗?

【问题讨论】:

    标签: php wordpress woocommerce orders coupon


    【解决方案1】:

    请尝试以下操作,这将添加一个逗号分隔的应用优惠券代码字符串及其各自的折扣金额:

    $order  = wc_get_order( $order_id ); // If needed
    $output = array(); // Initializing
    
    // loop through order items "coupon"
    foreach( $order->get_items('coupon') as $item_id => $item ){
        // Get the coupon array data in an unprotected array
        $data = $item->get_data();
        
        // Format desired coupon data for output
        $output[] = $data['code'] . ': ' . strip_tags( wc_price( $data['discount'] + $data['discount_tax'] ) );
    }
    
    $confirmation = str_ireplace("{order_items}", implode(', ', $output), $confirmation);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 2020-01-19
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多