Woocommerce 为特定用户角色设置最低订单

Woocommerce set minimum order for a specific user role

我有一个 php 代码,可以在整个站点范围内设置 100 个最低订单,效果很好。 我想使用相同的代码或通过克隆它并将其包装在 if() 语句中,为特定角色 'company' 设置不同的最小订单 250,只是我不知道如何编写它。非常感谢任何帮助。
这是醋栗代码(不要介意希伯来语文本,它只是错误消息,当条件不满足时):

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

谢谢!

首先您必须检索当前用户的角色。

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

现在要检查角色 company 是否在用户的角色中以确定最小值。

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

使用 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 文件中。它应该有效。

To format prices for display you can use the dedicated wc_price() formatting function.

相关: