phpwoocommercecheckoutcustom-fields

Hide custom field in woocommerce checkout based on specific role


I'm trying to disable a custom field that I've created in checkout page for whole-sellers. Looking for a way to disable the coupon field for shop manager in WooCommerce. I've inserted this code on my function.php, how i can do?

add_filter( 'woocommerce_checkout_fields' , 'field_cfpiva' );

function field_cfpiva( $fields ) {
     $fields['billing']['billing_cf'] = array(
        'label'     => __('Codice Fiscale / P.IVA', 'woocommerce'),
        'placeholder'   => _x('Codice Fiscale / P.IVA', 'placeholder', 'woocommerce'),
        'required'  => true,
        'class'     => array('form-row-wide'),
        'clear'     => true
     );

     return $fields;
}

 add_filter( 'woocommerce_admin_billing_fields' , 'admin_field_cfpiva' );

function admin_field_cfpiva( $fields ) {
     $fields['cf'] = array(
        'label' => __('Codice Fiscale / P.IVA', 'woocommerce'),
        'show'  => true
    );
    return $fields;
}   

function add_cf_in_invoice( $fields, $order ) {
    $new_fields = array();

    if( get_post_meta( $order->id, '_billing_cf', true ) ) {
        $new_fields['_billing_cf'] = array( 
            'label' => 'Codice Fiscale: ',
            'value' => get_post_meta( $order->id, '_billing_cf', true )
        );
    }    
    return array_merge( $fields, $new_fields );
}

add_filter( 'wcdn_order_info_fields', 'add_cf_in_invoice', 10, 2 );

/**
* Add the field to order emails
**/
add_filter('woocommerce_email_order_meta_keys', 
'my_woocommerce_email_order_meta_keys');

function my_woocommerce_email_order_meta_keys( $keys ) {
$keys['_billing_cf'] = 'Codice Fiscale';
return $keys;
}

Solution

  • Modify your function 'admin_field_cfpiva'. You need to put condition before adding field.

    Try following code -

    function admin_field_cfpiva( $fields ) {
        $user = wp_get_current_user();
        if ( !in_array( 'shop_manager', (array) $user->roles ) ) {   
    
             $fields['cf'] = array(
                  'label' => __('Codice Fiscale / P.IVA', 'woocommerce'),
                  'show'  => true
             );
        }
        return $fields;
    }