php - 如何隐藏添加到购物车按钮的特定角色和产品类别 Woocommerce
问题描述
我已经尝试过此代码但无法正常工作,并且此站点在技术上很困难:
function remove_add_to_cart_for_user_role() {
//set product category
$terms = 'produk-toko';
$targeted_user_role = 'customer'; // The slug in "lowercase"
$user_data = get_userdata(get_current_user_id());
if ( in_array( $targeted_user_role, $user_data->roles ) ) && ! is_user_logged_in(){
if(has_terms($terms, 'product_cat')) {
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');
怎么了?
解决方案
您的 if 条件有一些错字和错误。您的 if 条件在检查后立即被调用in_array
并且!is_user_logged_in
有额外的空格。所以你必须改变你的 if 条件
if ( in_array( $targeted_user_role, $user_data->roles ) ) && ! is_user_logged_in(){
至
if ( in_array( $targeted_user_role, $user_data->roles ) && !is_user_logged_in() ){
如下重写函数以解决错误。
function remove_add_to_cart_for_user_role(){
//set product category
$terms = 'produk-toko';
$targeted_user_role = 'customer'; // The slug in "lowercase"
$user_data = get_userdata(get_current_user_id());
if ( in_array( $targeted_user_role, $user_data->roles ) && !is_user_logged_in() ){
if(has_terms($terms, 'product_cat')){
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');