我想通过订单的自定义订单状态更改产品的类别。我发现 Change product category once the order status get completed 确实很有帮助。
但是我要更改的产品不是结帐产品,而是保存为订单元的商品。
这是保存订单商品元的代码
add_filter( 'woocommerce_add_cart_item_data', 'get_ship_item_name', 9999, 2 );
function get_ship_item_name( $cart_item, $product_id ) {
if ( isset( $_POST['ship_item'] ) ) {
$cart_item['ship_item'] = $_POST['ship_item'];
}
return $cart_item;
}
add_action( 'woocommerce_add_order_item_meta', 'save_posted_field_into_order', 9999, 2 );
function save_posted_field_into_order( $itemID, $values ) {
if ( ! empty( $values['ship_item'] ) ) {
$product = wc_get_product( $values['ship_item'] );
$product_name = $product->get_name();
wc_add_order_item_meta( $itemID, 'Item to ship', $product_name );
}
}
我尝试了以下代码。但这不起作用。
//auto change category to shipped
add_action('woocommerce_order_status_changed', 'change_category_to_shipped', 10, 1);
function change_category_to_shipped( $order_id ) {
// set your category ID or slug
$your_category = 'Shipped'; // or $your_category = 123;
$order = wc_get_order( $order_id );
$order_status = $order->post->post_status;
if ( $order->has_status( 'awaiting-shipment' ) ) {
foreach ( $order->get_items() as $item_id => $item_values ) {
$product_id = $item_data['product_id'];
$item_data = $item_values->get_data();
wp_set_object_terms( $product_id, $your_category, 'product_cat' );
}
}
}
当订单状态更改为“等待发货”时,如何从不同订单的订单元中获取产品ID并更改产品类别?