简体   繁体   中英

How to hide add to cart button specific role and product category Woocommerce

I have tried this code but isn't working, and this site is technically difficult:

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');

What's wrong?

Your if condition has some typo and errors. Your if condition was called right after checking in_array and !is_user_logged_in had extra spaces. So you have to change your if condition from

if ( in_array( $targeted_user_role, $user_data->roles ) ) && ! is_user_logged_in(){

to

if ( in_array( $targeted_user_role, $user_data->roles ) && !is_user_logged_in() ){

Rewrite function as below to resolve the error.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM