Разделение продуктов на заказы на основе метаданных продукта (пункт назначения)Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Разделение продуктов на заказы на основе метаданных продукта (пункт назначения)

Сообщение Anonymous »

У меня есть собственное решение для магазина woocommerce. При добавлении продукта в корзину открывается страница сведений о доставке, где клиент вводит данные (номер клиента, пункт назначения и т. д.). Затем кладет товар в корзину и продвигается вперед. Пункт назначения добавляется в корзину вместе с товаром. Теперь я хотел бы разделить заказ в зависимости от назначения продукции. Это означает, что продукты с одним и тем же местом назначения делятся на один заказ, а продукты с разными местами назначения — на отдельные заказы. Я зарегистрировал данные, и основное поле назначения правильно отображается в корзине и мета-заказе, поэтому проблема должна быть в коде, который разделяет продукты на заказы.
В настоящее время я код следующий:

Код: Выделить всё

/* Dividing orders with multiple products and delivery destinations into different orders */
add_action( 'woocommerce_checkout_order_processed', 'split_order_by_destination', 10, 1 );

function split_order_by_destination( $order_id ) {
$main_order = wc_get_order( $order_id );
if ( ! $main_order ) {
write_to_wc_log( 'Main order not found for order ID: ' . $order_id );
return;
}

$destination_groups = [];

// Group order items by `Destination` meta
foreach ( $main_order->get_items() as $item_id => $item ) {
$destination = $item->get_meta( 'Destination', true );
write_to_wc_log( 'Order Item ID: ' . $item_id . ', Destination: ' . $destination );

if ( ! $destination ) {
$destination = 'default'; // Handle items without a destination
}

write_to_wc_log( 'Processing Item ID: ' . $item_id . ', Destination: ' . $destination );

if ( ! isset( $destination_groups[ $destination ] ) ) {
$destination_groups[ $destination ] = [];
}

$destination_groups[ $destination ][] = $item;
}

write_to_wc_log( 'Destination Groups: ' . print_r( $destination_groups, true ) );

if ( empty( $destination_groups ) ) {
write_to_wc_log( 'No destination groups found. Exiting splitting process.' );
return;
}

// Process each destination group
foreach ( $destination_groups as $destination => $items ) {
$new_order = wc_create_order();

if ( ! $new_order ) {
write_to_wc_log( 'Failed to create new order for destination: ' . $destination );
continue;
}

// Copy customer details from the main order
$new_order->set_address( $main_order->get_address( 'billing' ), 'billing' );
$new_order->set_address( $main_order->get_address( 'shipping' ), 'shipping' );

foreach ( $items as $item ) {
$product = wc_get_product( $item->get_product_id() );

if ( $product ) {
$new_order->add_product(
$product,
$item->get_quantity(),
[
'subtotal' => $item->get_subtotal(),
'total'    => $item->get_total(),
'tax'      => $item->get_subtotal_tax(),
]
);
write_to_wc_log( 'Added Product ID: ' . $product->get_id() . ' to order for Destination: ' . $destination );
}
}

$new_order->calculate_totals();
$new_order->save();

write_to_wc_log( 'Created New Order ID: ' . $new_order->get_id() . ' for Destination: ' . $destination );
$new_order->add_order_note( 'Order created for destination: ' . $destination );
}

// Optionally cancel the main order
$main_order->update_status( 'cancelled', 'Order split into multiple orders by destination.' );
}
Назначения фиксируются правильно, но разделение по какой-то причине не происходит. Есть идеи?

Подробнее здесь: https://stackoverflow.com/questions/792 ... estination
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»