Home > Net >  Set state by default blank for guest customers on WooCommerce checkout page
Set state by default blank for guest customers on WooCommerce checkout page

Time:04-21

I have tried the below code to make the default state for visitors blank, so they have to manually choose it.

I want it only for non logged in users, cause I would like the state to be preselected if a registered customer goes to checkout, because probably WooCommerce will have kept his state from when he was registered!

add_filter( 'default_checkout_billing_state', 'change_default_checkout_state' );
add_filter( 'default_checkout_shipping_state', 'change_default_checkout_state' );
function change_default_checkout_state() {
    if ( ! is_user_logged_in() && is_checkout() ) {
    return ''; //set it to blank.
}
}

Unfortunately the above code works even for logged in users. Any advice?

CodePudding user response:

Make sure that there is always is something to return outside a condition when using filter hooks. Otherwise you get the chance that if the condition is not met, nothing will be returned or that you will receive an error message.

So you get:

function filter_default_checkout_state( $default, $input ) {
    // NOT logged in
    if ( ! is_user_logged_in() ) {
        return null;
    }

    return $default;
}
add_filter( 'default_checkout_billing_state', 'filter_default_checkout_state', 10, 2 );
add_filter( 'default_checkout_shipping_state', 'filter_default_checkout_state', 10, 2 );

CodePudding user response:

add_filter('default_checkout_shipping_state', 'default_checkout_default_state', 10, 2);
add_filter('default_checkout_billing_state', 'default_checkout_default_state', 10, 2);

function default_checkout_default_state($default_value, $input_field) {
    if (!is_user_logged_in()) {
        return null;
    }
    return $default_value;
}

This is the correct hook used for this return apply_filters( 'default_checkout_' . $input, $value, $input ); line 1270 in woocommerce/includes/class-wc-checkout.php. There is always two parameters for this hook and there is no hook default_checkout_shipping_state with single parameter.

  • Related