Add downloads in Woocommerce downloadable product programmatically

一世执手 提交于 2019-12-08 13:22:33

You should better use WC_Product and WC_Product_Download methods. I have revisited your code renaming/shortening a bit your variables names.

The code:

//This is my custom function which returns attachment id after file upload
$zip_attachment_id = upload_music_files( $music_id, $music_zip ); 

$file_name = $music_zip['name'];
$file_url  = wp_get_attachment_url( $zip_attachment_id );
$download_id = md5( $file_url );

// Creating an empty instance of a WC_Product_Download object
$pd_object = new WC_Product_Download();

// Set the data in the WC_Product_Download object
$pd_object->set_id( $download_id );
$pd_object->set_name( $file_name );
$pd_object->set_file( $file_url );

// Get an instance of the WC_Product object (from a defined product ID)
$product = wc_get_product( $music_id ); // <=== Be sure it's the product ID

// Get existing downloads (if they exist)
$downloads = $product->get_downloads();

// Add the new WC_Product_Download object to the array
$downloads[$download_id] = $pd_object;

// Set the complete downloads array in the product
$product->set_downloads($downloads);
$product->save(); // Save the data in database

Tested and works

Now you have to be sure that your $music_id variable is the product ID in:

$product = wc_get_product( $music_id );

If not you should get directly the WC_Product object from global $product;

OR the product ID from global $post; and $product_id = $post->ID;, making some changes in the code:

global $post;
$product = wc_get_product( $post->ID );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!