Woocommerce устанавливает минимальный заказ для определенной роли пользователя - PullRequest
0 голосов
/ 26 февраля 2019

У меня есть php-код, который устанавливает минимальный размер 100 сайтов и работает хорошо.Я хочу установить другой минимальный заказ 250 для конкретной роли «компания», используя тот же код или путем его клонирования и преобразования в оператор if (), только я понятия не имею, как его написать.Буду признателен за любую помощь.
Это код смородины (не обращайте внимания на текст на иврите, это просто сообщения об ошибках, когда условие не выполняется):

// Set a minimum dollar amount per order
add_action( 'woocommerce_check_cart_items', 'spyr_set_min_total' );
function spyr_set_min_total() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
    global $woocommerce;

    // Set minimum cart total
    $minimum_cart_total = 100;

    // Total we are going to be using for the Math
    // This is before taxes and shipping charges
    $total = WC()->cart->subtotal;

    // Compare values and add an error is Cart's total
    // happens to be less than the minimum required before checking out.
    // Will display a message along the lines of
    // A Minimum of 10 USD is required before checking out. (Cont. below)
    // Current cart total: 6 USD 
    if( $total <= $minimum_cart_total  ) {
        // Display our error message
        wc_add_notice( sprintf( '<strong>לקוח יקר, יש צורך במינימום הזמנה 
של %s %s₪ על מנת לבצע רכישה באתר.</strong>'
            .'<br />סכום הביניים בעגלה הינו: %s %s₪',
            $minimum_cart_total,
            get_option( 'woocommerce_currency_symbol'),
            $total,
            get_option( 'woocommerce_currency_symbol') ),
        'error' );
    }
  }
}

Спасибо!

Ответы [ 2 ]

0 голосов
/ 27 февраля 2019

Попробуйте следующее, используя current_user_can(), поэтому в вашем коде:

// Set a minimum amount per order (and user role)
add_action( 'woocommerce_check_cart_items', 'set_min_total_per_user_role' );
function set_min_total_per_user_role() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {

        // Set minimum cart total
        $minimum_cart_total = current_user_can('company') ? 250 : 100;

        // Total (before taxes and shipping charges)
        $total = WC()->cart->subtotal;

        // Add an error notice is cart total is less than the minimum required
        if( $total <= $minimum_cart_total  ) {
            // Display our error message
            wc_add_notice( sprintf( '<strong>Dear customer, minimum order of %s is required to make a purchase on your site.</strong> <br>
                Your actual cart amount is: %s',
                wc_price($minimum_cart_total),
                wc_price($total)
            ), 'error' );
        }
    }
}

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

Для форматирования цен для отображения вы можете использовать специальную функцию wc_price().

Связано: Применить скидку для конкретного пользователяроль в Woocommerce

0 голосов
/ 26 февраля 2019

Сначала вам нужно получить роли текущего пользователя.

$roles = is_user_logged_in() ? (array) wp_get_current_user()->roles : [];

Теперь вы хотите проверить, входит ли роль company в роли пользователя, чтобы определить минимум.

$minimum_cart_total = in_array('company', $roles) ? 250 : 100;
...