Change programmatically Woocommerce cart items from virtual to physical

Viewed 285

I need to programmatically change a cart item from "virtual" to "physical" at some point in calculate_cart_item_totals in Woocommerce. Is this possible?

1 Answers

You can only change cart item (product) properties using woocommerce_before_calculate_totals hook. Now to change a cart item from "virtual" to "physical" you will use the WC_Product method set_virtual() as follows:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_data_replacement', 16 );
function custom_cart_item_data_replacement( $cart ) {

    foreach ( $cart->get_cart() as $cart_item ) {
        // Change virtual cart item to "physical"
        if( $cart_item['data']->get_virtual() ) {
            $cart_item['data']->set_virtual(false);
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related