首页 文章

在WooCommerce中删除特定用户角色的添加到购物车按钮

提问于
浏览
6

在我使用Divi主题和woocommerce的虚拟商店中,我有两组用户:最终用户和我的经销商,在我的终端客户端的情况下,只需要出现“购买”按钮 . 我的经销商已经只有“添加到订单”按钮(由YITH Request A Quote插件提供) . 如果怀疑如何删除转销商帐户的添加到购物车按钮,我知道使用代码:

remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

我从整个网站删除按钮,但我试图使用某种 if 只能定义一个组 . 像这样的东西:

$user = wp_get_current_user();
if ( in_array( 'Revenda', (array) $user->roles ) ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}

或这个:

if( current_user_can('revenda') ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}

我也在尝试这段代码:

function user_filter_addtocart_for_shop_page(){
    $user_role = get_user_role();
    $role_id = get_role('Revenda');
    if($user_role == $role_id){
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    }
}

get_user_role将从以下位置显示:

function get_user_role() {
    global $current_user;

    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);

    return $user_role;
}

我怎样才能做到这一点?

谢谢

1 回答

  • 3

    正确的代码可以执行您想要的操作(用户角色slug是小写的,我使用 get_userdata(get_current_user_id()) 来获取用户数据 .

    所以我改变了一下你的代码:

    function remove_add_to_cart_for_user_role(){
        // Set Here the user role slug
        $targeted_user_role = 'revenda'; // The slug in "lowercase"
        $user_data = get_userdata(get_current_user_id());
        if ( in_array( $targeted_user_role, $user_data->roles ) ) {
            remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        }
    }
    add_action('init', 'remove_add_to_cart_for_user_role');
    

    我已将代码嵌入到 init 钩子上触发的函数中 .

    此代码经过测试且功能齐全 .

    代码位于活动子主题(或主题)的function.php文件中 . 或者也可以在任何插件php文件中 .

相关问题