在Woocommerce中,仅限购物车中的特定用户角色

问题描述 投票:1回答:1

我为一个客户做了一个Woocommerce礼品店。他们的客户是其他业务,让他们的员工通过网上商店选择他们的礼物。每个企业都有1个登录,所有员工都使用。截至目前,每位用户只能在购物车中使用1件商品。如果选择了其他产品,它将覆盖之前的产品。

今天我被告知他们希望扩展,以便选择用户/用户角色可以在他们的购物车中拥有多个产品并“购买”它们。货币交易不直接在网上商店处理,因此购买产品会向我的客户发送一个列表,然后从那里获取

我用来施加此限制的当前代码如下:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_only_one_in_cart', 99, 2 );
function custom_only_one_in_cart( $passed, $added_product_id ) {

    // empty cart first: new item will replace previous
    wc_empty_cart();

    // display a message if you like
    wc_add_notice( 'Max number of items in cart reached!', 'notice' );

    return $passed;
}

因此,我正在寻找有关如何在特定用户或用户角色上实现此功能的想法,因此最终结果将是大多数用户只能选择一个,而少数选择用户可以选择更多。

我已经在寻找合适的解决方案,但我还没有找到一个解决方案。

该解决方案不必包含我提供的代码,无论是在当前状态还是在其变体中,都欢迎所有合适的解决方案。

任何帮助表示赞赏。

php wordpress woocommerce cart user-roles
1个回答
0
投票

在以下代码中,将根据已定义的允许用户角色限制将购物车添加到一个商品:

add_filter( 'woocommerce_add_to_cart_validation', 'user_roles_only_one_in_cart', 50, 3 );
function user_roles_only_one_in_cart( $passed, $product_id, $quantity ) {
    // HERE define the User roles that are allowed to buy multiple items:
    $allowed_user_roles = array('special_customer','administrator', 'shop_manager');

    $user = wp_get_current_user();

    if( array_intersect( $allowed_user_roles, $user->roles ) )
        return $passed;

    // Check if cart is empty
    if( ! WC()->cart->is_empty() ){
        // display an error notice
        wc_add_notice( __("Only one item in cart is allowed!", "woocommerce"), "error" );
        // Avoid add to cart
        $passed = false;
    }

    return $passed;
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。

enter image description here

对于用户角色的创建和管理,您可以使用User Role Editor插件(例如)。

© www.soinside.com 2019 - 2024. All rights reserved.