Add downloads in Woocommerce downloadable product programmatically

前端 未结 1 844
囚心锁ツ
囚心锁ツ 2020-12-10 23:18

I am creating a Woocommerce site where I wanna give vendors to upload products from their front end. But I stuck on a point where I am trying to add woocommerce downloadable

相关标签:
1条回答
  • 2020-12-11 00:00

    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 );
    
    0 讨论(0)
提交回复
热议问题