We recently imported a large number of orders and files from and older legacy / custom Ecommerce site into a Woocommerce site.
There are a lot of tales to tell in this adventure, but a big one was getting all of these files attached correctly to the product variations downloadable file.
It took a while to find a good solution, but thankfully Chris Hawkins had a good answer for me over on Stack Overflow.
Here is essentially what my solution looked like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
$limit = 10000; $offset = 0 * $limit; $orders = get_posts( array( 'post_type' => 'shop_order', 'post_status' => 'wc-completed', 'posts_per_page' => $limit, 'offset' => $offset ) ); foreach ( $orders as $order ) { regen_woo_downloadable_product_permissions( $order->ID, true ); } /** * Regenerate the WooCommerce download permissions for an order * @param Integer $order_id */ function regen_woo_downloadable_product_permissions( $order_id ){ // Remove all existing download permissions for this order. // This uses the same code as the "regenerate download permissions" action in the WP admin (https://github.com/woocommerce/woocommerce/blob/3.5.2/includes/admin/meta-boxes/class-wc-meta-box-order-actions.php#L129-L131) // An instance of the download's Data Store (WC_Customer_Download_Data_Store) is created and // uses its method to delete a download permission from the database by order ID. $data_store = WC_Data_Store::load( 'customer-download' ); $data_store->delete_by_order_id( $order_id ); // Run WooCommerce's built in function to create the permissions for an order (https://docs.woocommerce.com/wc-apidocs/function-wc_downloadable_product_permissions.html) // Setting the second "force" argument to true makes sure that this ignores the fact that permissions // have already been generated on the order. wc_downloadable_product_permissions( $order_id, true ); } |
This only needs to be run once for each order so this can be run from almost anywhere. Make sure to update your offset until you make it through all your orders AND that you already have all your files in place.
That is it! I hope this helps someone!