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

Wordpress Gravity Form插件自定义文件上传UI后如何展示选中的文件名?

Gravity Form自定义文件上传文件名显示实现方案

方案1:适配现有改造的轻量实现

你已经通过gform_field_content过滤器完成了UI改造,直接追加JS监听事件即可,不需要改动现有PHP/CSS代码:

  • 将以下JS代码加入主题自定义JS区块,或者对应表单的自定义脚本设置中即可生效
// 兼容Gravity Form AJAX加载、多页表单场景
document.addEventListener('gform_post_render', function() {
  // 选中所有Gravity Form文件上传输入框
  const fileInputs = document.querySelectorAll('.gfield input[type="file"]');
  fileInputs.forEach(input => {
    input.addEventListener('change', function(e) {
      const fileName = e.target.files[0]?.name || '';
      // 替换为你自定义UI中用来展示文件名的容器选择器
      const fileNameDisplay = this.closest('.gfield').querySelector('.your-custom-filename-container');
      if (fileNameDisplay) {
        fileNameDisplay.textContent = fileName ? fileName : '未选择任何文件';
      }
    })
  })
})
  • 如果你实现的是多文件上传功能,遍历e.target.files数组拼接所有文件名即可
  • 用gform_post_render事件绑定是为了避免表单AJAX刷新、多页跳转后事件失效

方案2:维护成本更低的集成实现(更优方案)

直接把文件名展示容器、交互逻辑都整合到你已经在使用的gform_field_content过滤器中,所有逻辑统一管理,换主题、新增表单都不需要重复配置:

add_filter('gform_field_content', function($content, $field, $value, $lead_id, $form_id) {
  // 仅处理文件上传字段
  if ($field->type == 'fileupload') {
    // 这里保留你之前写的自定义UI相关代码,新增以下逻辑即可
    $custom_output = '<div class="custom-upload-wrapper">';
    // 原生输入框保留,你可以通过CSS设置opacity:0隐藏,用来触发系统文件选择器
    $custom_output .= $content;
    // 新增文件名展示容器
    $custom_output .= '<span class="custom-filename-text">未选择文件</span>';
    // 内嵌当前字段专属交互逻辑,自动匹配字段ID,多字段场景不会冲突
    $custom_output .= "<script>
      document.addEventListener('gform_post_render', function() {
        const uploadInput = document.querySelector('.gfield_{$field->id} input[type=\"file\"]');
        const nameDisplay = document.querySelector('.gfield_{$field->id} .custom-filename-text');
        if(uploadInput && nameDisplay) {
          uploadInput.addEventListener('change', e => {
            nameDisplay.textContent = e.target.files[0]?.name || '未选择文件';
          })
        }
      })
    </script>";
    $custom_output .= '</div>';
    return $custom_output;
  }
  // 非文件上传字段返回原始内容
  return $content;
}, 10, 5);

该方案的优势:

  • 所有UI、交互逻辑都在同一个钩子中管理,不会出现CSS/JS和字段不匹配的问题
  • 自动适配多个文件上传字段、多个表单场景,不会出现ID冲突
  • 完全兼容Gravity Form原生的文件大小校验、格式校验功能,不需要额外做适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:09:01