Search code examples
woocommercehook-woocommerce

WooCommerce renaming a digital download file


I've been using woocommerce to sell a few digital goods. I have set the following setting "Append a unique string to filename for security" And I was wondering if there is a way to rename the file back to it's original name when the customer downloads it.

For example the filename is product-9j978f.zip and when the customer downloads it would be renamed to product.zip instead.

Thank you and any help would be gladly appreciated


Solution

  • Here is the code

    /**
     * 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 );
    
        // You can generate a new file using Product ID if you need to.
        $new_file_name = 'New File Name';
    
        // Join the new file name with file extension with (.).
        return join( '.', array( $new_file_name, $filetype['ext'] ) );
    }
    add_filter( 'woocommerce_file_download_filename', 'change_woocommerce_file_download_filename', 10, 2 );
    

    You get 2 parameters in this filter hook. 1: Filename 2: Product ID then you can do the name change according to your need and return the file name.

    NOTE: new file name should have a file extension with it.