Получайте данные о купонах из заказов WooCommerce

Я создал в WooCommerce два настраиваемых типа купонов:

function custom_discount_type( $discount_types ) {
    $discount_types['cash_back_fixed'] =__( 'Cash Back fixed discount', 'woocommerce' );
     $discount_types['cash_back_percentage'] =__( 'Cash Back Percentage discount', 'woocommerce' );
         return $discount_types;

     }

add_filter( 'woocommerce_coupon_discount_types', 'custom_discount_type',10, 1);

Я хотел бы получить тип скидки после того, как статус заказа будет «выполнен», например:

function wc_m_move_order_money_to_user( $order_id, $old_status, $new_status ){

    if( $order->get_used_coupons() ) {
        if ($coupon->type == 'cash_back_fixed'){ 
           $coupons_amont =  ???
           ....

       }
    }
}

Но $coupon->type не работает.

Как я могу получить типы купонов, использованные в заказе?
И как я могу получить исходную сумму купона ?.

Спасибо


person Gaurav    schedule 07.07.2017    source источник
comment
Как узнать сумму купона (а не суммы купона, использованные в заказе)   -  person Gaurav    schedule 08.07.2017
comment
Спасибо за поддержку. А теперь удалил повторяющиеся вопросы.   -  person Gaurav    schedule 08.07.2017


Ответы (2)


Обновление 3

Начиная с WooCommerce 3.7, теперь вы должны использовать метод WC_Abstract _ 2_ в объекте экземпляра WC_Order, чтобы получить использованные купоны из заказа, поскольку метод get_used_coupons() устарел.

Итак, вы замените в коде:

foreach( $order->get_used_coupons() as $coupon_code ){

by:

foreach( $order->get_coupon_codes() as $coupon_code ){

Затем вы можете получить подробную информацию о купоне, например:

foreach( $order->get_coupon_codes() as $coupon_code ) {
    // Get the WC_Coupon object
    $coupon = new WC_Coupon($coupon_code);

    $discount_type = $coupon->get_discount_type(); // Get coupon discount type
    $coupon_amount = $coupon->get_amount(); // Get coupon amount
}

Обновление 2

Во-первых, вы больше не можете получить доступ к свойствам объектов WC, начиная с WooCommerce 3.

Теперь вам следует использовать WC_Coupon методы получения, чтобы получить сведения о купоне < / strong> из экземпляра WC_Coupon Object…

В вашем случае вам необходимо использовать get_discount_type() или метод is_type( 'cash_back_fixed' )

Вот как это сделать:

// Get an instance of WC_Order object
$order = wc_get_order( $order_id );

// Coupons used in the order LOOP (as they can be multiple)
foreach( $order->get_used_coupons() as $coupon_code ){

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

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

    // Now you can get type in your condition
    if ( $coupon->get_discount_type() == 'cash_back_percentage' ){
        // Get the coupon object amount
        $coupon_amount1 = $coupon->get_amount();
    }

    // Or use this other conditional method for coupon type
    if( $coupon->is_type( 'cash_back_fixed' ) ){
        // Get the coupon object amount
        $coupon_amount2 = $coupon->get_amount();
    }
}

Чтобы получить размер скидки по купонам (а также использовать методы типов купонов), вот способ:

$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( 'cash_back_fixed' ) || $coupon->is_type( 'cash_back_percentage' ) ){

        // 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();
    }
}

Итак, чтобы получить цену купона, мы используем метод WC_Coupon get_amount().

person LoicTheAztec    schedule 08.07.2017

В моем случае мне нужно было изменить новые заказы на предварительный заказ (пользовательский статус уже добавлен в систему), если использовался конкретный купон и заказ был оплачен (так, если задействован статус обработки).

function change_status_to_preorder($order_id) {
    
    $order          = new WC_Order($order_id);
    $coupon_codes   = $order->get_coupon_codes();
    
    if(in_array('MYCOUPON', $coupon_codes) && $order->get_status() == 'processing') {
        $order->update_status('wc-pre-order', 'AUTO: note to shop manager');
    }
}
add_action('woocommerce_new_order', 'change_status_to_preorder', 1, 1);
person Meloman    schedule 07.04.2021