Product Filename Renaming

WooCommerce stores downloadable product by renaming the file and appending some 6 alphabet giberish like podrne.

To deliver a proper product filename to customer we need to add a code snippet in WordPress site’s functions file (usually functions.php in your theme) or in a custom plugin.

1. Access Your Theme’s Functions File:

In your WordPress Dashboard, go to Appearance → Theme Editor. In the Theme Files list on the right, find and open the functions.php file.

2. Paste the Code:

Copy the following code and paste it at the end of your functions.php file.

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

    // Here, define how you want the new file name to be generated
    // For example, using the product's name or SKU (you can customize this part).
    $product = wc_get_product( $product_id );
    $new_file_name = 'Product_' . $product->get_name(); // You can customize the naming logic.

    // Join the new file name with file extension.
    return join( '.', array( $new_file_name, $filetype['ext'] ) );
}
add_filter( 'woocommerce_file_download_filename', 'change_woocommerce_file_download_filename', 10, 2 );

3. Customization of File Naming Logic:

In the line $new_file_name = 'Product_' . $product->get_name(); you can change how the new file name is generated.

For example:

$product->get_name() will use the product name.

$product->get_sku() will use the product SKU.

You can combine them or add any custom string to generate the desired name.

$new_file_name = 'Download_' . $product->get_sku() . '_v1';  // Uses the SKU with a version number.

4. Save Changes:

Once you’ve added the code, click Update File to save your changes.

Last updated