Preserve spaces in file titles for downloadable audiofiles in WooCommerce/Wordpress

Viewed 54

I have a client who is going to sell downloadable audiofiles with the WooCommerce plugin: The filenames of the audiofiles contains spaces, which is very important for the artist behind the audiofiles. But the spaces have been changed by Wordpress into hyphens when uploaded to the media library. I found the code below and tried adding it to my functions.php to restore the original filenames, but surely something is missing!

What code should I write (and where) to call each ID product number and make the output file name change to the original title of the song? Any help would be appreciated.

WooCommerce renaming a digital download file

1 Answers

/**
 * Change the downloadable file name
 *
 * @param string $filename Downloadable file name.
 * @param int    $product_id WC product id.
 * @return string
 */
function change_woocommerce_file_download_filename( $filename, $product_id ) {
    // Get the file extension from the processed file name.
    $filetype = wp_check_filetype( $filename );

// Replace hyphens in new file name
    $new_file_name = str_replace("-", " ", $filename);

    // Join the new file name with file extension with (.).
    return $new_file_name;
}

add_filter( 'woocommerce_file_download_filename', 'change_woocommerce_file_download_filename', 10, 2 );

Related