简体   繁体   中英

Get used coupon codes and related discount amounts from WooCommerce orders

I need to insert in a custom plugin the code to get the name of the discount codes I enter in the settings, the discount obtained with the code and the total.

Based on Get coupon data from WooCommerce orders answer code, I have inserted the following code:

$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);

But the only information it brings back to me, when I do an echo is the word "array".

What am I doing wrong? Any help?

Try the following instead, that will add a coma separated string of applied coupon codes with their respective discount amount:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM