WordPressでカスタムPHP formで画像ファイルをメールに添付

Pocket

フォーム

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="store_img" id="store_img" accept=".jpg,.JPG,.jpeg,.JPEG,.png,.PNG">
    <?php wp_nonce_field( 'add_store', 'add_store'); ?>
    <input type="submit" value="店登録" >
</form>

 

nonceで判定、処理。name=”store_img”

if ( isset( $_POST['add_store'] ) && wp_verify_nonce( $_POST['add_store'], 'add_store' ) ){
   
    // $attachemnts
    $attachments = array();

    // process image
    if( $_FILES ){

        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );
        $attach_id = media_handle_upload('store_img', $new_post_id);
        if (is_numeric($attach_id)) {
            $img_url = wp_get_attachment_url( $attach_id );
            $img_path = get_attached_file( $attach_id );
            $attachments[] = $img_path;
        }
        
    }

    $content = 'hogehoge';
    
    wp_mail(array('youremail'), '店登録 ', $content, "", $attachments );

}

 

メールの送信者の修正も忘れずに

add_filter( 'wp_mail_from', 'sender_email' );
function sender_email( $original_email_address ) {
    return 'noreply@hogehoge.com';
}

add_filter( 'wp_mail_from_name', 'sender_name' );
function sender_name( $original_email_from ) {
    return 'ほげほげ';
}

 

この記事を書いた人