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

时间:2016-12-06 13:59:09

标签: php wordpress woocommerce cart product

在我使用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 个答案:

答案 0 :(得分:4)

正确的代码可以执行您想要的操作(用户角色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文件中。