You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WooCommerce可下载文件添加额外字段?

为WooCommerce可下载文件添加额外字段的解决方案

1. 在产品编辑页的可下载文件区域添加自定义字段

通过woocommerce_product_download_fields钩子,可在每个可下载文件的编辑项后插入自定义字段。以下是添加“文件备注”字段的示例代码:

add_filter( 'woocommerce_product_download_fields', 'add_custom_download_field' );
function add_custom_download_field( $fields ) {
    $fields['custom_note'] = array(
        'label'       => __( '文件备注', 'woocommerce' ),
        'description' => __( '添加该下载文件的额外说明信息', 'woocommerce' ),
        'type'        => 'text',
        'placeholder' => __( '输入备注内容', 'woocommerce' ),
        'default'     => ''
    );
    return $fields;
}

2. 保存自定义字段的数据

使用woocommerce_admin_process_product_object钩子处理字段数据保存,确保编辑产品时输入的内容能被存储:

add_action( 'woocommerce_admin_process_product_object', 'save_custom_download_field_data' );
function save_custom_download_field_data( $product ) {
    if ( isset( $_POST['_downloadable_files'] ) ) {
        $downloads = $_POST['_downloadable_files'];
        foreach ( $downloads as $key => $download ) {
            if ( isset( $download['custom_note'] ) ) {
                $product->update_meta_data( '_download_custom_note_' . $key, sanitize_text_field( $download['custom_note'] ) );
            }
        }
    }
}

3. 在订单下载区域显示自定义字段

如果需要让用户在订单下载页面看到备注内容,可通过woocommerce_downloadable_file_buttons钩子输出:

add_filter( 'woocommerce_downloadable_file_buttons', 'display_custom_download_field_in_order', 10, 4 );
function display_custom_download_field_in_order( $buttons, $download_id, $product_id, $download ) {
    $custom_note = get_post_meta( $product_id, '_download_custom_note_' . $download_id, true );
    if ( ! empty( $custom_note ) ) {
        $buttons .= '<p class="download-custom-note">' . esc_html( $custom_note ) . '</p>';
    }
    return $buttons;
}

使用说明

  • 将代码添加到WordPress主题的functions.php文件,或创建自定义插件存放代码(推荐后者,避免主题更新丢失代码)。
  • 可根据需求修改字段名、标签、描述等内容,比如将custom_note替换为你需要的字段标识。

内容的提问来源于stack exchange,提问作者madzhidoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:42:36