Unable to Override WooCommerce Checkout Fields

I’ve created a custom WooCommerce checkout field with Woothemes Checkout Field Editor labeled “po_number”. I would like the PO Number checkout field to only display for the user role “distributor”.

So far I’ve been unsuccessful in overriding the checkout fields. I’m using WordPress 4.5.1 / Woocommerce 2.5.5. Here’s the code I’ve placed in my child theme’s functions.php. I’ve also tested to make sure it is not a theme conflict.

Read More

Any help is greatly appreciated.

This is my code:

function custom_override_checkout_fields( $fields ) {

    if ( ! current_user_can( 'distributor' ) && isset( $fields['billing']['po_number'] ) ) {
        unset($fields['billing']['po_number']);

    }
     return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

Related posts

1 comment

  1. The current_user_can() function is related to capabilities of the user roles, but not to detect the user roles themselves. For that reason is not working in your code.

    You need to set a conditional function for this purpose (user roles):

    function is_user_role( $role, $user_id = null ) {
        if ( is_numeric( $user_id ) ) {
            $user = get_userdata( $user_id );
        } else {
            $user = wp_get_current_user();
        }
        if ( empty( $user ) ) {
            return false;
        }
        if ( in_array( $role, (array) $user->roles ) == 1) {
            return true;
        } else {
            return false;
        }
    }
    

    Then in your code you can use that function:

    function custom_override_checkout_fields( $fields ) {
        if ( !is_user_role( 'distributor' ) && isset( $fields['billing']['po_number'] ) ) {
            unset($fields['billing']['po_number']);
        }
            return $fields;
    }
    add_filter( 'woocommerce_checkout_fields', 'custom_override_checkout_fields' );
    

    This should work in your code.

Comments are closed.