Last active
March 2, 2023 19:07
-
-
Save mostafasoufi/4908ef781b449bc6917ffd369b7d70c7 to your computer and use it in GitHub Desktop.
Regenerate bulk order downloads by WP CLI in WooCommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Order Command | |
*/ | |
class OrderCommand | |
{ | |
/** | |
* Regenerate order downloads. | |
* | |
* ## OPTIONS | |
* | |
* <id>... | |
* : One or more IDs of orders to re generate. | |
*/ | |
function regenerate_downloads($args, $assoc_args) | |
{ | |
foreach ($args as $orderId) { | |
$order = wc_get_order($orderId); | |
if ($order instanceof \Automattic\WooCommerce\Admin\Overrides\OrderRefund) { | |
WP_CLI::error("Order #{$order->get_id()} is refunded!", false); | |
continue; | |
} | |
if (!$order->is_download_permitted()) { | |
WP_CLI::error("Order #{$order->get_id()} is not permitted!", false); | |
continue; | |
} | |
// 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->get_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->get_id(), true); | |
WP_CLI::success("Order #{$order->get_id()}: Download generated successfully!"); | |
} | |
} | |
} | |
\WP_CLI::add_command('wc_custom', '\License\OrderCommand'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Commands
wp wc_custom regenerate_downloads {orderId} wp wc_custom regenerate_downloads $(wp post list --post_type=shop_order --format=ids --posts_per_page=10000)