I want set an alternative address if the cart has a product type that is equal on a specific type.
<?php
add_filter( 'woocommerce_checkout_create_order', 'mbm_alter_shipping', 10, 1 );
function mbm_alter_shipping ($order) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $product => $values) {
$product->get_product();
if ($product->is_type('octopus')) {
$address = array(
'company' => 'Test',
'email' => '[email protected]',
'phone' => '777-777-777-777',
'city' => 'London',
'state' => '',
'postcode' => '12345',
'country' => 'UK'
);
}
$order->set_address( $address, 'shipping' );
}
return $order;
}
?>
But when trying to place an order, I get an Internal Server Error and the order is not placed.
What I am doing wrong? Any help is appreciated.
The woocommerce_checkout_create_order
is an action hook, your code is outdated and full of mistakes… Try to use the following instead:
add_action( 'woocommerce_checkout_create_order', 'alter_order_shipping_address', 10, 2 );
function alter_order_shipping_address( $order, $data ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Targetting a custom product type
if ( $cart_item['data']->is_type('octopus') ) {
// Changing shipping address
$order->set_address( array(
'company' => 'Test',
'email' => '[email protected]',
'phone' => '777-777-777-777',
'city' => 'London',
'state' => '',
'postcode' => '12345',
'country' => 'UK'
), 'shipping' );
break; // stop the loop
}
}
}
Code goes in functions.php file of the active child theme (or active theme). It should works.