更改 WooCommerce 产品的所有文件名字段

问题描述 投票:0回答:1

我有许多插件使用我的 WooCommerce 可下载产品文件的文件名字段来显示下载按钮! WooCommerce 也在此处执行此操作以在用户面板中显示文件名:

woocommerce/templates/order/order-downloads.php

与:

echo '<a href="' . esc_url( $download['download_url'] ) . '" class="woocommerce-MyAccount-downloads-file button alt">' . esc_html( $download['download_name'] ) . '</a>';

我不想编辑所有产品的文件名字段我也不想编辑这些插件的代码

有没有办法象征性地和假设性地更改和设置所有文件名?我认为 WooCommerce 应该引入我选择的文件名。例如,告诉大家所有文件的文件名是“免费下载”,而不是“ps-action.zip”

我认为 woocommerce 在这里创建并处理这个: 1-woocommerce/includes/class-wc-download-handler.php 2-woocommerce/src/Admin/API/Reports/Downloads/Controller.php

1-class-wc-download-handler.php 第 218 行:

public static function download( $file_path, $product_id ) {
        if ( ! $file_path ) {
            self::download_error( __( 'No file defined', 'woocommerce' ) );
        }

        $filename = basename( $file_path );

        if ( strstr( $filename, '?' ) ) {
            $filename = current( explode( '?', $filename ) );
        }

        $filename = apply_filters( 'woocommerce_file_download_filename', $filename, $product_id );

2-Controller.php 第 84 行:

// Figure out file name.
// Matches https://github.com/woocommerce/woocommerce/blob/4be0018c092e617c5d2b8c46b800eb71ece9ddef/includes/class-wc-download-handler.php#L197.
$product_id = intval( $data['product_id'] );
$_product   = wc_get_product( $product_id );

// Make sure the product hasn't been deleted.
if ( $_product ) {
    $file_path                   = $_product->get_file_download_path( $data['download_id'] );
    $filename                    = basename( $file_path );
    $response->data['file_name'] = apply_filters( 'woocommerce_file_download_filename', $filename, $product_id );
    $response->data['file_path'] = $file_path;
} else {
    $response->data['file_name'] = '';
    $response->data['file_path'] = '';
}

也许我们可以通过这种方式应用过滤器来显示我们的文本(只是显示它,而不是将其插入到文件名字段中) 我是初学者,谢谢你帮助我

php wordpress woocommerce filenames hook-woocommerce
1个回答
0
投票

您可以使用 woocommerce_file_download_filename 过滤器更改显示的文件名,而无需实际修改产品的文件名字段。此过滤器会在文件名显示之前应用于文件名,因此不会更改服务器上的实际文件。

以下是如何使用此过滤器显示自定义文本而不是实际文件名的示例:

PHP 代码:

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

function custom_download_filename($filename, $product_id) {
// You can replace "free download" with any text you want.
return 'free download';
}

将其添加到主题的functions.php 文件中。这会将所有可下载产品的显示文件名更改为“免费下载”。

请注意,这只会影响显示,不会影响您的服务器或 WooCommerce 数据库中的实际文件名。这对用户来说是视觉上的变化,不会影响下载的功能。

© www.soinside.com 2019 - 2024. All rights reserved.