WordPress: caricare un file nella Media Library ed allegarlo in una e-mail

WordPress: caricare un file nella Media Library ed allegarlo in una e-mail

In WordPress è semplice caricare un file nella Media Library ed allegarlo in un'e-mail.

Presupponendo che il valore dell'attributo name del campo di tipo file del form sia file, la soluzione è la seguente.


function my_upload_send_file() {
    $posted_data =  isset( $_POST ) ? $_POST : array();
	$file_data = isset( $_FILES ) ? $_FILES : array();
	$data = array_merge( $posted_data, $file_data );
	$attachment_id = media_handle_upload( 'file', 0 );

    if( !is_wp_error( $attachment_id ) ) {
        $to = get_bloginfo( 'admin_email' );
        $subject = __( 'New upload', 'textdomain' );
        $message = wp_get_attachment_url( $attachment_id );
        $headers = array( 'From: My Site <noreply@site.tld>' );
        $attachments = array( get_attached_file( $attachment_id ) );

        wp_mail( $to, $subject, $message, $headers, $attachments );
    }
}

Torna su