Change WooCommerce order status based on approved status and specific order item

axkjgtzd  于 2022-10-22  发布在  PHP
关注(0)|答案(1)|浏览(155)

I try to change a WooCommerce order status to "Processing" when the current status is "Approved" and the order includes a specific product ( id = 10).
I have attempted the code below but it is not working. I am quite new to php and would appreciate any guidance!

  1. add_action('woocommerce_order_status_changed', 'ts_auto_complete_business_cards');
  2. function ts_auto_complete_business_cards($order_id)
  3. {
  4. if ( ! $order_id ) {
  5. return;
  6. }
  7. global $product;
  8. $order = wc_get_order( $order_id );
  9. if ($order->data['status'] == 'approved') {
  10. $items=$order->get_items();
  11. foreach ( $items as $item ) {
  12. $product_id = $item->get_product_id();
  13. if ($product_id!="10")
  14. {
  15. $order->update_status( 'completed' );
  16. }
  17. }
  18. }
  19. }
mwg9r5ms

mwg9r5ms1#

  • woocommerce_order_status_changed has 4 parameters
  • This line -> if ($product_id!="10") says NOT equal, you also compare with a string and not with a numerical value

Try it this way

  1. function action_woocommerce_order_status_changed( $order_id, $old_status, $new_status, $order ) {
  2. // Compare
  3. if( $old_status === 'approved' ) {
  4. // Get items
  5. $items = $order->get_items();
  6. foreach ( $items as $item ) {
  7. // Get product id
  8. $product_id = $item->get_product_id();
  9. if ($product_id == 10 ) {
  10. $order->update_status( 'processing' );
  11. break;
  12. }
  13. }
  14. }
  15. }
  16. add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed', 10, 4 );
展开查看全部

相关问题