I am new on stackoverflow, so I apologize if my message is not correct.
I am importing WooCommerce downloadable products from a CSV. I manage to import all the details and product image, except the downloadable file - File URL, which should be the same image as the product but in full size.
I'm trying to do it automatically in functions.php but I can't.
I found this code here: Add programmatically a downloadable file to Woocommerce products
add_action( 'woocommerce_admin_process_product_object', 'auto_add_downloadable_file', 50, 1 );
function auto_add_downloadable_file( $product ){
// Get downloads (if there is any)
$downloads = (array) $product->get_downloads();
// Only added once (avoiding repetitions
if( sizeof($downloads) == 0 ){
// Get post thumbnail data
$thumb_id = get_post_thumbnail_id( $product->get_id() );
$src_img = wp_get_attachment_image_src( $thumb_id, 'full');
$img_meta = wp_get_attachment_metadata( $thumb_id, false );
// Prepare download data
$file_title = $img_meta['image_meta']['title'];
$file_url = reset($src_img);
$file_md5 = md5($file_url);
$download = new WC_Product_Download(); // Get an instance of the WC_Product_Download Object
// Set the download data
$download->set_name($file_title);
$download->set_id($file_md5);
$download->set_file($file_url);
$downloads[$md5_num] = $download; // Insert the new download to the array of downloads
$product->set_downloads($downloads); // Set new array of downloads
}
}
This code works when I manually access a product from the admin panel, and update it. But it doesn't work when I just import products.
It also doesn't work if I do a bulk edit. I have thousands of products, so doing it manually one by one is not an option.
I also tried to change the hook in the add_action, I tried all of these, but none of them worked:
add_action( 'woocommerce_admin_process_product_object', 'auto_add_downloadable_file', 50, 1 );
add_action( 'woocommerce_new_product', 'auto_add_downloadable_file', 50, 1 );
add_action( 'new_to_publish', 'auto_add_downloadable_file', 50, 1 );
add_action( 'woocommerce_product_import_inserted_product_object', 'auto_add_downloadable_file', 50, 1 );
add_action( 'woocommerce_product_import_before_import', 'auto_add_downloadable_file', 50, 1 );
add_action( 'woocommerce_update_product', 'auto_add_downloadable_file', 50, 1 );
add_action( 'transition_post_status', 'auto_add_downloadable_file', 50, 1 );
add_action( 'save_post', 'auto_add_downloadable_file', 50, 1 );
Can anyone help me to edit the code so that it works directly when importing products, or if it's not possible, that it works when editing in bulk.
I've been testing for several days and I can't get it. Thank you so much.