Включите рассчитанный предел скидки корзины в Woocommerce

Я пытаюсь собрать скидку WooCommerce без использования купонов, и все работает, кроме функции «ограничения».

Каждый новый покупатель получит 20% (впервые покупатели) на свою покупку, но эти 20% не могут и не должны превышать 15 долларов.

Вот код, который является плагином, и мне нужна помощь, чтобы "сказать ему", что если сумма скидки на корзину больше 15, удалите ее и поставьте 15.

Вот что не работает: if ( $discount = $discountValue/100 >15) return $discountLimit;

Полный код:

    function loc_first_order_add_admin_menu(  ) { 
    add_submenu_page( 'woocommerce', 'First Order Discount', 'First Order Discount', 'manage_options', 'woocomerce_first_order_discount', 'first_order_add_options_page' );
}

function loc_first_order_add_settings_init(  ) { 
    register_setting( 'pluginPage', 'first_order_add_settings' );
    add_settings_section( 'first_order_add_pluginPage_section', __( 'This will give all first time customers a discount of your choice without using a coupon.', 'woo-first-discount' ), '', 'pluginPage' );
    add_settings_field( 'first_order_choose', __( 'Type', 'woo-first-discount' ), 'loc_first_order_options', 'pluginPage', 'first_order_add_pluginPage_section' );
    add_settings_field( 'first_order_add_value',  __( 'Value', 'woo-first-discount' ), 'loc_first_order_number', 'pluginPage',  'first_order_add_pluginPage_section' );
    add_settings_field( 'first_order_add_limit',  __( 'Limit', 'woo-first-discount' ), 'loc_first_order_limit', 'pluginPage',   'first_order_add_pluginPage_section' );
}

function loc_first_order_options(  ) { 
    $options = get_option( 'first_order_add_settings' );
    ?>
    <input id = "off" type='radio' name='first_order_add_settings[first_order_choose]' <?php checked( $options['first_order_choose'], 'off' ); ?> value='off'>
    <label for = "off"><?php echo __( 'Disable', 'woo-first-discount' ); ?></label>
    <br>
    <input id = "fixed" type='radio' name='first_order_add_settings[first_order_choose]' <?php checked( $options['first_order_choose'], 'fixed' ); ?> value='fixed'>
    <label for = "fixed"><?php echo __( 'Fixed', 'woo-first-discount' ); ?></label>
    <br>
    <input id = "percent" type='radio' name='first_order_add_settings[first_order_choose]' <?php checked( $options['first_order_choose'], 'percent' ); ?> value='percent'>
    <label for = "percent"><?php echo __( 'Percentage', 'woo-first-discount' ); ?></label>
    <?php
}


function loc_first_order_limit(  ) { 
    $options = get_option( 'first_order_add_settings' );
    ?>
    <input type='number' min = "0" name='first_order_add_settings[first_order_add_limit]' value='<?php echo $options['first_order_add_limit']; ?>'>
    <?php
}

function loc_first_order_number(  ) { 
    $options = get_option( 'first_order_add_settings' );
    ?>
    <input type='number' min = "0" name='first_order_add_settings[first_order_add_value]' value='<?php echo $options['first_order_add_value']; ?>'>
    <?php
}

function first_order_add_options_page(  ) { 
    ?>
    <form action='options.php' method='post'>
        <h2><?php echo __( 'First Order Discount', 'woo-first-discount' ); ?></h2>
        <?php
        settings_fields( 'pluginPage' );
        do_settings_sections( 'pluginPage' );
        submit_button();
        ?>
    </form>
    <?php
}

function loc_first_order_discount() {
    global $wpdb, $woocommerce;
    if ( is_user_logged_in() ) {
        $customer_id = get_current_user_id();
        $orderNumCheck = wc_get_customer_order_count( $customer_id );
        $options = get_option( 'first_order_add_settings' );
        $discountType = $options['first_order_choose'];
        $discountValue = $options['first_order_add_value'];
        $discountLimit = $options['first_order_add_limit'];

        if ($orderNumCheck == 0 and $discountType != 'off') {
            $subtotal = WC()->cart->cart_contents_total;
            if ($discountType == 'fixed') {
                WC()->cart->add_fee( 'First Time Order Discount ', -$discountValue );
            } else {
                if ( $discount = $discountValue/100 >15) return $discountLimit;
                WC()->cart->add_fee( 'First Time Order Discount ', -$subtotal*$discount );
            }
        } else {
            WC()->cart->add_fee( 'First Time Order Discount ', 0 );
        }
    }
}

add_action( 'woocommerce_cart_calculate_fees', 'loc_first_order_discount' );

add_filter( 'woocommerce_checkout_login_message', 'loc_return_customer_message' );
function loc_return_customer_message() {
return '<b>Have you shopped with us before?</b><br>Did you know that all first time orders automatically receives a 20% discount with a maximum value of 15 dollars?<br>';
}

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

Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
1
0
118
1

Ответы 1

Я пересмотрел весь код вашей функции, так как он немного устарел. Попробуй это:

add_action( 'woocommerce_cart_calculate_fees', 'loc_first_order_discount', 20, 1 );
function loc_first_order_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! is_user_logged_in() )
        return; // Only for logged in users

    $customer_id   = get_current_user_id();
    $orderNumCheck = wc_get_customer_order_count( $customer_id );
    $options       = get_option( 'first_order_add_settings' );
    $discountType  = $options['first_order_choose'];

    if ( $orderNumCheck > 0 || $discountType == 'off' )
        return; // Exit

    $discountValue = $options['first_order_add_value'];
    $discountLimit = $options['first_order_add_limit'];
    $subtotal      = $cart->cart_contents_total;
    $discount_text = __('First Time Order Discount ', 'woocommerce');
    $discount      = 0;


    if ($discountType == 'fixed') {
        $discount = $discountValue;
    } else {
        $discount = $subtotal / 0.20; // 20%

        if ( $discount > $discountLimit )
            $discount = $discountLimit;
    }

    if ( $discount > 0 )
        $cart->add_fee( $discount_text, -$discount );
}

Код находится в файле function.php вашей активной дочерней темы (или активной темы). Теперь все должно работать, как ожидалось ...

Другие вопросы по теме