I have not tested this code, most use the same logic we use in WooCommerce… You just need to change the $product_id
and and run it where you deem appropriate:
global $wpdb;
$product_id = 1; // Change to your product ID.
// Get orders.
$orders = $wpdb->get_results( $wpdb->prepare( "SELECT items.order_id FROM {$wpdb->prefix}woocommerce_order_items AS items LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id WHERE itemmeta.meta_key = '_product_id' AND itemmeta.meta_value = %d;", $product_id ) );
if ( ! empty( $orders ) ) {
foreach ( $orders as $_order ) {
$order_id = (int) $_order->order_id;
if ( 1 == get_post_meta( $order_id, '_download_permissions_granted', true ) ) {
return; // Only do this once.
}
$order = wc_get_order( $order_id );
if ( count( $order->get_items() ) > 0 ) {
foreach ( $order->get_items() as $item ) {
$_product = $order->get_product_from_item( $item );
if ( $_product && $_product->exists() && $_product->is_downloadable() ) {
$downloads = $_product->get_files();
foreach ( array_keys( $downloads ) as $download_id ) {
wc_downloadable_file_permission( $download_id, $item['variation_id'] > 0 ? $item['variation_id'] : $item['product_id'], $order, $item['qty'] );
}
}
}
}
update_post_meta( $order_id, '_download_permissions_granted', 1 );
do_action( 'woocommerce_grant_product_download_permissions', $order_id );
}
}
We do not support custom code here, then make a backup of your database and good luck.