Native UI: Auto-Apply Coupon When Scheduled Order Updated by Customer

In this example a user wants to automatically apply a coupon whenever a Scheduled Order is updated by a customer using the Native UI Scheduled Order display option ( My Account > Scheduled Orders). a dev customizes the update request to QPilot to contain the coupon they want to apply using the "autoship_after_autoship_update_schedule_items_handler_success" action.

Example

/**
 * Auto Apply a Coupon on Update Items button in Native UI
 *
 * @param int $order_id The Scheduled order
 */
function xx_auto_apply_coupon_on_update_items( $order_id ){

  // Allow the auto-apply code to be adjusted, in this case coupon code 'KLDA25' will be applied
  $coupon_code = apply_filters( 'xx_auto_apply_coupon_code', 'KLDA25', $order_id );

  // Retrieve the scheduled order
  $order = autoship_get_scheduled_order( $order_id );

  // HACK: Remove spaces Incorrectly added by QPilot
  $order_coupons          = $order->coupons;
  $original_order_coupons = preg_replace('/\s+/', '', $order_coupons );

  // Check if its already applied and skip.
  if ( array_key_exists( $coupon_code, array_flip( $original_order_coupons ) ) )
  return;

  // Run QPilot validation for the scheduled order and code then apply.
  $valid = autoship_validate_and_apply_scheduled_order_coupon( $order_id, $coupon_code, $order );

}
add_action( "autoship_after_autoship_update_schedule_items_handler_success", 'xx_auto_apply_coupon_on_update_items', 10, 1 );