WordPress Contact Form 7:如何通过代码添加多个邮件附件?
解决Contact Form 7自定义代码添加多个附件失效问题
你的代码在添加单个自定义附件时正常,但添加多个就丢失所有附件,核心原因是任意一个附件路径错误或文件不存在时,Contact Form 7会直接忽略全部附件,同时原代码没有处理表单后台已配置的附件,也缺乏错误排查机制。
以下是修复后的代码,同时解决了这些问题:
add_action('wpcf7_before_send_mail', 'custom_attach_files_to_email'); function custom_attach_files_to_email($contact_form) { $submission = WPCF7_Submission::get_instance(); if (!$submission) return; $uploaded_files = $submission->uploaded_files(); $attachments = []; // 收集表单用户上传的有效文件 foreach ($uploaded_files as $file_path) { if (file_exists($file_path)) { $attachments[] = $file_path; } } // 定义要添加的自定义附件列表 $custom_files = [ WP_CONTENT_DIR . '/uploads/files/file.txt', WP_CONTENT_DIR . '/uploads/files/file_2.txt' ]; // 逐个检查自定义文件是否存在,仅添加有效文件 foreach ($custom_files as $custom_file) { if (file_exists($custom_file)) { $attachments[] = $custom_file; } else { // 记录错误日志,方便排查哪个文件出问题 error_log('CF7自定义附件不存在:' . $custom_file); } } $mail = $contact_form->prop('mail'); // 合并表单后台已配置的附件(避免覆盖原有设置) if (!empty($mail['attachments'])) { $existing_attachments = explode(',', $mail['attachments']); foreach ($existing_attachments as $existing_file) { $existing_file = trim($existing_file); if (!empty($existing_file) && file_exists($existing_file)) { $attachments[] = $existing_file; } } } // 仅当有有效附件时才更新邮件配置 if (!empty($attachments)) { $mail['attachments'] = implode(',', $attachments); $contact_form->set_properties(['mail' => $mail]); } }
关键修复点说明
- 强制文件存在检查:每个附件路径都会验证是否真实存在,避免单个无效文件导致全部附件失效
- 保留原有附件配置:不会覆盖你在CF7表单后台设置的附件
- 错误日志记录:如果某个自定义文件找不到,会在WordPress错误日志(
wp-content/debug.log)中留下记录,方便定位问题 - 精简逻辑:提前判断提交实例是否存在,避免无效代码执行
额外排查步骤
- 确认
/wp-content/uploads/files/目录存在,且权限设置为755 - 确认
file.txt和file_2.txt文件存在,文件权限设置为644 - 开启WordPress调试模式(
wp-config.php中设置WP_DEBUG = true),查看错误日志排查路径问题
内容的提问来源于stack exchange,提问作者Вадим Можейко
相关产品推荐
相关产品推荐

