Advertisement
vapvarun

Save downloadable files for a WooCommerce product - Modified

Aug 26th, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | Software | 0 0
  1. /**
  2.  * Save downloadable files for a WooCommerce product.
  3.  *
  4.  * @param WC_Product $product  Product instance.
  5.  * @param array      $downloads  Array of download data.
  6.  *
  7.  * @return WC_Product
  8.  */
  9. protected function save_downloadable_files( $product, $downloads ) {
  10.     $download_files = [];
  11.  
  12.     foreach ( $downloads as $download_id => $download_data ) {
  13.         // Skip if the file URL is empty
  14.         if ( empty( $download_data['file'] ) ) {
  15.             continue;
  16.         }
  17.  
  18.         // Initialize a new download object
  19.         $download = new WC_Product_Download();
  20.         $download->set_id( $download_id );
  21.         $download->set_name( ! empty( $download_data['name'] ) ? $download_data['name'] : wc_get_filename_from_url( $download_data['file'] ) );
  22.        
  23.         // Apply the filter to the file path
  24.         $filtered_file_path = apply_filters( 'woocommerce_file_download_path', $download_data['file'], $product, $download_id );
  25.         $download->set_file( $filtered_file_path );
  26.        
  27.         $download_files[] = $download;
  28.     }
  29.  
  30.     // Apply a filter to the array of downloads before setting it on the product
  31.     $filtered_download_files = apply_filters( 'woocommerce_product_download_files', $download_files, $product );
  32.  
  33.     // Set the downloads on the product
  34.     $product->set_downloads( $filtered_download_files );
  35.  
  36.     return $product;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement