如何从wordpress'媒体上传器添加到wp_mail的附件? (WordPress的)

时间:2016-03-18 12:13:11

标签: php jquery wordpress

我正在开发一个插件,我有一个后端页面,显示输入文本字段和按钮。当您单击该按钮时,会打开wordpress'媒体上传器,您可以选择一个文件。该文件的URL将插入到该输入字段值中。在这里你可以看到代码:

HTML:

<div class="wp-uploader">
    <input id="upload_image" type="text" size="36" name="upload_image" value="" />
    <input class="button" id="upload_image_button" type="button" value="Legg til PDF fra mediabibliotek" />
</div>

JQuery的:

jQuery(document).ready(function($){


    var custom_uploader;


    $('#upload_image_button').click(function(e) {

        e.preventDefault();

        //If the uploader object has already been created, reopen the dialog
        if (custom_uploader) {
            custom_uploader.open();
            return;
        }

        //Extend the wp.media object
        custom_uploader = wp.media.frames.file_frame = wp.media({
            title: 'Velg en PDF',
            button: {
                text: 'Velg'
            },
            multiple: false
        });

        //When a file is selected, grab the URL and set it as the text field's value
        custom_uploader.on('select', function() {
            attachment = custom_uploader.state().get('selection').first().toJSON();
            $('#upload_image').val(attachment.url);
        });

        //Open the uploader dialog
        custom_uploader.open();

    });


});

我想知道这个选择的文件将作为wp_mail的附件发送。

这是我的功能:

function dd_send_email(){

    $email_sent = false;

    // get email template data
    $email_template_object = dd_get_current_options();
    $url = $_POST['upload_image'];
    $mail_attachment = array(WP_CONTENT_DIR=>$url);    

    // if email template data was found
    if ( !empty( $email_template_object ) ):

        // setup wp_mail headers
        $wp_mail_headers = array('Content-Type: text/html; charset=UTF-8');

        // use wp_mail to send email
        $email_sent = wp_mail( array( 'example@email.com') , $email_template_object['dd_emne_forhaandsbestilling'], $email_template_object['dd_email_text_forhaandsbestilling'], $wp_mail_headers, $mail_attachment );
    endif;

    return $email_sent;

}

但这不起作用。我仍然收到没有任何附件的电子邮件。我想我获取文件网址的方式是错误的,但我无法找到如何做到这一点。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我自己找到了答案。因为wp_mail需要像/uploads/2016/03/example.jpg那样的文件路径,所以我们必须将我们的url转换为这样的路径。

我通过更改dd_send_mail()中的以下内容并认为我可以与您分享来实现此目的:

// change url to path   
$dd_url = $_POST['upload_image'];
$dd_path = parse_url($dd_url);

// cut the path to right directory
$array = explode("/norskeanalyser/wp-content", $dd_path['path']);
unset($array[0]);
$text = implode("/", $array);

然后我将$text保存到$mail_attachment并在wp_mail中调用它,如上所述。

感谢大家的帮助!