From 886abe282d0917bc5a306e627f44e65f764e6ae5 Mon Sep 17 00:00:00 2001 From: Claudio Sanches Date: Thu, 13 May 2021 13:48:49 -0300 Subject: [PATCH] Allows set downloadable permissions to any downloadable product in any order --- includes/class-wc-ajax.php | 41 ++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/includes/class-wc-ajax.php b/includes/class-wc-ajax.php index b35d97d6590..e630d1db37d 100644 --- a/includes/class-wc-ajax.php +++ b/includes/class-wc-ajax.php @@ -795,22 +795,43 @@ class WC_AJAX { $loop = intval( $_POST['loop'] ); $file_counter = 0; $order = wc_get_order( $order_id ); - $items = $order->get_items(); + if ( ! $order->get_billing_email() ) { + wp_die(); + } + + $data = array(); + $items = $order->get_items(); + + // Check against order items first. foreach ( $items as $item ) { $product = $item->get_product(); - if ( ! in_array( $product->get_id(), $product_ids, true ) ) { - continue; - } - $files = $product->get_downloads(); - if ( ! $order->get_billing_email() ) { - wp_die(); + if ( $product && $product->exists() && in_array( $product->get_id(), $product_ids, true ) && $product->is_downloadable() ) { + $data[ $product->get_id() ] = array( + 'files' => $product->get_downloads(), + 'quantity' => $item->get_quantity(), + 'order_item' => $item, + ); + } + } + + foreach ( $product_ids as $product_id ) { + $product = wc_get_product( $product_id ); + + if ( isset( $data[ $product->get_id() ] ) ) { + $download_data = $data[ $product->get_id() ]; + } else { + $download_data = array( + 'files' => $product->get_downloads(), + 'quantity' => 1, + 'order_item' => null, + ); } - if ( ! empty( $files ) ) { - foreach ( $files as $download_id => $file ) { - $inserted_id = wc_downloadable_file_permission( $download_id, $product->get_id(), $order, $item->get_quantity(), $item ); + if ( ! empty( $download_data['files'] ) ) { + foreach ( $download_data['files'] as $download_id => $file ) { + $inserted_id = wc_downloadable_file_permission( $download_id, $product->get_id(), $order, $download_data['quantity'], $download_data['order_item'] ); if ( $inserted_id ) { $download = new WC_Customer_Download( $inserted_id ); $loop ++;