Search code examples
phpwordpresswoocommercecheckoutuser-roles

Hide "Ship to a different address" for a specific user role in Woocommerce 3


Plugin used: "User Role editor" to add extra roles.

Created a role: "SpecialCust"

I have tried to unset "ship to different address" if user has this roll but it's not really picking up the code as it seems.

function Unset_Shipping_adress() {
    // Get the user object.
    $user = get_userdata( $user_id );

    // Get all the user roles as an array.
    $user_roles = $user_meta->roles;

    // Check if the role you're interested in, is present in the array.
    if ( in_array( 'SpecialCust', $user_roles, true ) ) {
        add_filter( 'woocommerce_cart_needs_shipping_address', '__return_false');
    }
}

Solution

  • There are some missing parts in your code and it can be simplified. Try the following instead:

    add_action('init', 'unset_shipping_address' );
    function unset_shipping_address() {
        // HERE the targeted user roles
        $user_roles = array('SpecialCust', 'SpecialCust2', 'SpecialCust3');
    
        // Check user roles to hide “Ship to a different address”
        foreach( $user_roles as $user_role ) {
            if ( current_user_can( sanitize_title( $user_role ) ) ) {
                add_filter( 'woocommerce_cart_needs_shipping_address', '__return_false');
                break; // Found, we stop the loop
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should work.

    Reminder: to hide “Ship to a different address” in Woocommerce we just use:

    add_filter( 'woocommerce_cart_needs_shipping_address', '__return_false');