Авто применить купон на основе общей суммы, потраченной в магазине WooCommerce - PullRequest
2 голосов
/ 16 апреля 2019

Мне нужно применить ранее созданный купон в корзине WooCommerce, основанный на общей сумме, потраченной в магазине зарегистрированными пользователями. Например, если пользователь уже потратил 300 долларов США или более в предыдущих заказах, в следующем заказе автоматически применяется купон «xxx».

на основе " Автоматическое применение купона на основе количества товаров в корзине в Woocommerce " ветка ответов, вот что у меня до сих пор:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_cart_items_count', 25, 1 );
function auto_add_coupon_based_on_cart_items_count( $user_id, $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Setting and initialising variables
    $coupon = 'descuentolealtad'; // <===  Coupon code
    $matched = false;
    $customer = new WC_Customer( $user_id );

    if( $customer->get_total_spent >= 60 ){
        $matched = true; // Set to true
    }

    // If conditions are matched add coupon is not applied
    if( $matched && ! $cart->has_discount( $coupon )){
        // Apply the coupon code
        $cart->add_discount( $coupon );

        // Optionally display a message
        wc_add_notice( __('Descuento de Lealtad aplicado'), 'notice');
    }
    // If conditions are not matched and coupon has been appied
    elseif( ! $matched && $cart->has_discount( $coupon )){
        // Remove the coupon code
        $cart->remove_coupon( $coupon );

        // Optionally display a message
        //wc_add_notice( __('Descuento de Lealtad removido'), 'error');
    }
}   

Я пытаюсь использовать выделенную функцию get_total_spent() от woocommerce, но у меня пустой экран.

Любая помощь приветствуется.


Редактировать

Это мой рабочий код, очень отличающийся, поскольку я использую отрицательную плату:

add_action('woocommerce_cart_calculate_fees' , 'discount_based_on_customer_orders', 10, 1);
function discount_based_on_customer_orders( $cart_object ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;  
    // Getting "completed" customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed' // Only orders with status "completed"
    ) );
    // Orders count
    $customer_orders_count = count($customer_orders);
    // The cart total
    $cart_total = WC()->cart->get_total(); // or WC()->cart->get_total_ex_tax()

    // First customer order discount
    if( empty($customer_orders) || $customer_orders_count == 0 ){
        $discount_text = __('Loyalty Discount', 'woocommerce');
        $discount = -7;
    }

}

1 Ответ

3 голосов
/ 16 апреля 2019

Обновлено - В вашем коде много ошибок, таких как:

  • Для этого хука есть только один переменный аргумент: $cart… а не $user_id и $cart
  • Начиная с Woocommerce 3, используйте метод get_total_spent(), а не свойство get_total_spent.
  • Сначала необходимо проверить, что пользователь также вошел в систему.

Вместо этого используйте следующий пересмотренный код:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_total_spent', 10, 1 );
function auto_add_coupon_based_on_total_spent( $cart ) {

    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Setting and initialising variables
    $coupon = 'summer'; // <===  Coupon code
    $spent_amount = 60;

    $customer = new WC_Customer(get_current_user_id());

    // If conditions are matched add coupon is not applied
    if( $customer->get_total_spent() >= $spent_amount && ! $cart->has_discount( $coupon )){
        // Apply the coupon code
        $cart->add_discount( $coupon );

        // Optionally display a message
        wc_add_notice( __('Descuento de Lealtad aplicado'), 'notice');
    }
    // If conditions are not matched and coupon has been appied
    elseif($customer->get_total_spent() < $spent_amount && $cart->has_discount( $coupon )){
        // Remove the coupon code
        $cart->remove_coupon( $coupon );
    }
}

Код входит в файл function.php вашей активной дочерней темы (или активной темы).Должно лучше работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...