首页 > 解决方案 > 在 PHP 中使用 wp_mail 发送多个附件

问题描述

我正在尝试使用 发送多个附件wp_mail(),在出现一些附件名称问题(它显示类似phprTxfd.pdf而不是file_name.pdf)之后,我成功显示了附件的名称。

但是当我尝试发送多个附件时,它只显示邮件中的第一个附件,而不显示其他附件。

这是我的代码

function my_custom_email_content_type( $content_type ) {
                return 'text/html';
            }

            if ( ! function_exists( 'wp_handle_upload' ) ) {
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
            }


                $files = $_FILES[ 'fichier' ];

            $upload_overrides = array( 'test_form' => false );

                $attachments = array();

            foreach ( $files['name'] as $key => $value ) {
                if ( $files[ 'name' ][ $key ] ) {
                    $file = array(
                        'name'     => $files[ 'name' ][ $key ],
                        'type'     => $files[ 'type' ][ $key ],
                        'tmp_name' => $files[ 'tmp_name' ][ $key ],
                        'error'    => $files[ 'error' ][ $key ],
                        'size'     => $files[ 'size' ][ $key ]
                    );
                    $movefile = wp_handle_upload(
                        $file,
                        $upload_overrides
                    );
                    $attachments[] = $movefile[ 'file' ];
                }
            }

                add_filter(
                 'wp_mail_content_type',
                 'my_custom_email_content_type'
             );
    wp_mail($to, $subject, $message, $headers, $attachments);

我认为问题来了,$files = $_FILES['fichier']只需将第一个文件保存在变量中。

我试图把 $files 作为一个数组,但它不起作用。

谢谢。

编辑

print_r($files)显示这个:

数组 ( [名称] => 数组 ( [0] => logo1.png [1] => logo2.png ) [类型] => 数组 ( [0] => image/png [1] => image/png ) [tmp_name] => 数组 ( [0] => C:\xamp\tmp\phpC62D.tmp [1] => C:\xamp\tmp\phpC62E.tmp ) [错误] => 数组 ( [0] => 0 [1] => 0) [大小] => 数组 ([0] => 4440 [1] => 7830))

当我尝试在我的文件输入多个中插入 2 个或多个文件时。

标签: phpwordpressfileemailattachment

解决方案


当我遇到这篇文章时,我遇到了同样的问题。

OP 在确定他们的问题时非常接近……我也按上述方式进行了设置,但没有收到我的任何附件。

事实证明,您需要将文件提交字段的“名称”设置为数组。在 OP 情况下,它应该设置为 name='fichier[]'

一旦我改变了它,我的多个文件就通过了。


推荐阅读