我读了很多以前的代码,我修复了这个,完全后端成本化,我需要这样的东西,我们在每个产品上添加序列号,但我们希望客户能按数量购买,希望对一些人有所帮助,
外接程序功能。主题/子主题或函数中包含的任何文件的php。php
在上一版中,我添加了对变体产品的支持
add_action( \'woocommerce_after_order_object_save\', \'split_order_items\', 10, 2 );
function split_order_items($order) {
$order_items = $order->get_items();
foreach ($order_items as $item) {
$quantity = $item->get_quantity(\'edit\');
$product = $item->get_product();
$included_cats = [24, 25];
$variable = false;
if ($product->is_type(\'variation\')) {
$variation_id = $product->get_id();
$variable_prod = $product;
$product = wc_get_product($product->get_parent_id());
$variable = true;
}
$category_id = get_the_terms($product->get_id(), \'product_cat\')[0]->term_id;
if ($product && $quantity > 1 && in_array($category_id, $included_cats)) {
if ($variable) {
$init_qty = $quantity;
$item->set_quantity(1);
if ($quantity > 1) $item->set_props([
\'subtotal\' => $item->get_subtotal(\'edit\') / ($init_qty ?: $quantity),
\'total\' => $item->get_total(\'edit\') / ($init_qty ?: $quantity),
\'subtotal_tax\' => $item->get_subtotal_tax(\'edit\') / ($init_qty ?: $quantity),
\'total_tax\' => $item->get_total_tax(\'edit\') / ($init_qty ?: $quantity),
]);
if ($quantity == 1) continue;
$quantity--;
} else {
$order->remove_item($item->get_id());
}
$taxes = $item->get_taxes();
for ($i = $quantity; $i > 0; $i--) {
$new_item = new WC_Order_Item_Product();
$new_taxes = [];
if ($variable) {
$new_item->set_product_id($product->get_parent_id());
$new_item->set_variation_id($variation_id);
$new_item->set_variation(is_callable([$variable_prod, \'get_variation_attributes\']) ? $variable_prod->get_variation_attributes() : []);
$new_item->set_name($variable_prod->get_name());
$new_item->set_tax_class($variable_prod->get_tax_class());
} else {
$new_item->set_product($product);
}
if (!empty($taxes) && is_array($taxes)) {
foreach ($taxes as $taxes_key => $tax_values) {
$new_tax_values = [];
if (!empty($tax_values) && is_array($tax_values)) {
foreach ($tax_values as $tax_key => $tax_value) {
$new_tax_values[$tax_key] = $tax_value / $quantity;
}
}
$new_taxes[$taxes_key] = $new_tax_values;
}
}
$new_item->set_backorder_meta();
$new_item->set_props([
\'quantity\' => 1,
\'subtotal\' => $item->get_subtotal(\'edit\') / ($variable ? 1 : $quantity),
\'total\' => $item->get_total(\'edit\') / ($variable ? 1 : $quantity),
\'subtotal_tax\' => $item->get_subtotal_tax(\'edit\') / ($variable ? 1 : $quantity),
\'total_tax\' => $item->get_total_tax(\'edit\') / ($variable ? 1 : $quantity),
\'taxes\' => $new_taxes,
]);
$order->add_item($new_item);
}
}
}
remove_action(\'woocommerce_after_order_object_save\', \'split_order_items\', 10);
$order->save();
add_action(\'woocommerce_after_order_object_save\', \'split_order_items\', 10, 1);
}