Bositkhon Sultonov
Bositkhon Sultonov

Reputation: 705

Enable 'Ship to a different address' check box for specific products in Woocommerce

How to make 'Ship to a different address' mandatory for specific products and disable it for ordinary products? I have tried to use this code, but it did not work for me.

add_filter( 'woocommerce_available_payment_gateways', 'conditionally_disable_cod_payment_method', 10, 1);
function conditionally_disable_cod_payment_method( $gateways ){

    $products_ids = array(793, 796);

    foreach ( WC()->cart->get_cart() as $cart_item ){

        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if (in_array( $cart_item['product_id'], $products_ids ) ){

            add_filter( 'woocommerce_ship_to_different_address_checked', '__return_true' );

        }
    }
    return $gateways;
}

Upvotes: 1

Views: 500

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

Try the following instead:

add_filter( 'woocommerce_ship_to_different_address_checked', 'filter_cart_needs_shipping_address');
function filter_cart_needs_shipping_address( $checked ) {

    $products_ids = array(793, 796);
    $found = $others_found = false;

    foreach ( WC()->cart->get_cart() as $cart_item ){
        if (in_array( $cart_item['data']->get_id(), $products_ids ) ){
            $found = true;
        } else {
            $others_found = true;
        }
    }

    if( $found && ! $others_found )
        $checked = true;

    return $checked;
} 

Upvotes: 2

Related Questions