基于用户角色的Woocommerce最低订单总数

时间:2020-06-27 20:33:47

标签: php wordpress woocommerce cart hook-woocommerce

我正在使用Woocommerce Minimum Order Amount的代码段设置最低订单总数。但是我想为每个用户角色设置不同的最低要求。

我有一些自定义用户角色:wholesale_priceswholesale_vat_excdistributor_prices。我想使代码根据使用角色来工作,每个角色的最小使用量不同。

这是我的代码:

// Minimum order total

add_action( 'woocommerce_check_cart_items', 'wc_minimum_order_amount' );
 
function wc_minimum_order_amount() {
    // Set this variable to specify a minimum order value
    $minimum = 300;

    if ( WC()->cart->subtotal < $minimum ) {

        if( is_cart() ) {

            wc_print_notice( 
                sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' , 
                    wc_price( $minimum ), 
                    wc_price( WC()->cart->subtotal )
                ), 'error' 
            );

        } else {

            wc_add_notice( 
                sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' , 
                    wc_price( $minimum ), 
                    wc_price( WC()->cart->subtotal )
                ), 'error' 
            );

        }
    }

1 个答案:

答案 0 :(得分:2)

使用Wordpress条件函数current_user_can(),例如:

add_action( 'woocommerce_check_cart_items', 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
    // minimum order value by user role
    if ( current_user_can('distributor_prices') )
        $minimum = 3000; 
    elseif ( current_user_can('wholesale_prices') )
        $minimum = 1000;
    elseif ( current_user_can('wholesale_vat_exc') )
        $minimum = 600;
    else 
        $minimum = 300; // default

    if ( WC()->cart->subtotal < $minimum ) {

        if( is_cart() ) {
            wc_print_notice( sprintf( 
                'You must have an order with a minimum of %s to place your order, your current order total is %s.' , 
                wc_price( $minimum ), 
                wc_price( WC()->cart->subtotal )
            ), 'error' );
        } else {
            wc_add_notice( sprintf( 
                'You must have an order with a minimum of %s to place your order, your current order total is %s.' , 
                wc_price( $minimum ), 
                wc_price( WC()->cart->subtotal )
            ), 'error' );
        }
    }
}

代码在活动子主题(或活动主题)的functions.php文件中。应该可以。