以编程方式在Woocommerce可下载产品中添加下载

Ish*_*ved 1 php wordpress product download woocommerce

我正在创建一个Woocommerce网站,我想在这里向供应商提供从前端上传产品的信息。但是我坚持要尝试添加woocommerce可下载产品。

这是我当前的代码:

//Let's upload the download file Zip 
    $zipattachment_id = upload_music_files($music_ID, $musicZip); //This is my custom function which returns attachment id after file upload

    $download_file_name = $musicZip['name'];
    $download_file_url  = wp_get_attachment_url($zipattachment_id);
    $md5_download_num = md5( $download_file_url );

    //creating array of download product
    $downloadable_file[$md5_download_num] = array(
        'id'   =>  $md5_download_num,
        'name'   =>  $download_file_name,
        'file'   =>  $download_file_url,
        'previous_hash' => ''
    );
    $downloadMusic = serialize($downloadable_file);

    // adding downloadble file with the new array
    add_post_meta( $music_ID, '_downloadable_files', $downloadMusic );
Run Code Online (Sandbox Code Playgroud)

但是,当我从后端打开产品编辑时,没有可下载文件退出。

这是序列化数组的示例返回:

a:1:{s:32:"22618d7f028803f57f98ab6b21277387";a:4:{s:2:"id";s:32:"22618d7f028803f57f98ab6b21277387";s:4:"name";s:5:"1.zip";s:4:"file";s:71:"http://mydomain/wp-content/uploads/2017/12/5a2e22cecaca6_1.zip";s:13:"previous_hash";s:0:"";}}
Run Code Online (Sandbox Code Playgroud)

我正在使用最新版本的woocommerce,有人可以建议我做错了什么,正确的方法是什么?

Loi*_*tec 5

您应该更好地使用WC_ProductWC_Product_Download方法。我已经重新审视了您的代码,重命名/简称了您的变量名称。

代码:

//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
Run Code Online (Sandbox Code Playgroud)

经过测试和工作

现在,您必须确保$music_id变量是以下位置的产品ID

$product = wc_get_product( $music_id );
Run Code Online (Sandbox Code Playgroud)

如果没有,您应该直接WC_Productglobal $product;

来自global $post;和的产品ID $product_id = $post->ID;,对代码进行一些更改:

global $post;
$product = wc_get_product( $post->ID );
Run Code Online (Sandbox Code Playgroud)