如何在Wordpress中存储用户上传的文件?

如何在Wordpress中存储用户上传的文件?,wordpress,Wordpress,我正在构建一个自定义表单(不使用任何插件),从前端的用户而不是管理区域获取数据。表单元素之一是一个文件字段,用户可以在其中上载多个文件 Wordpress中存储用户生成文件的机制是什么?是否有任何帮助函数允许开发人员轻松存储文件?向用户添加新字段的wp api函数是“添加用户\元”函数 在我看来,您必须使用函数“add_user_meta”向用户添加一个新的自定义字段。然后,您应该使用“wp_insert_attachment”功能将上传的文件添加到媒体库中 阅读表单值 1-使用“wp插入附件”

我正在构建一个自定义表单(不使用任何插件),从前端的用户而不是管理区域获取数据。表单元素之一是一个文件字段,用户可以在其中上载多个文件


Wordpress中存储用户生成文件的机制是什么?是否有任何帮助函数允许开发人员轻松存储文件?

向用户添加新字段的wp api函数是“添加用户\元”函数

在我看来,您必须使用函数“add_user_meta”向用户添加一个新的自定义字段。然后,您应该使用“wp_insert_attachment”功能将上传的文件添加到媒体库中

阅读表单值

1-使用“wp插入附件”功能添加上传的文件。

2-使用“添加用户元”功能向用户添加字段。

3-将文件引用ID分配给用户字段。

以下是文档链接:

问候,,
Ed.

按“上载”按钮后,您将使用$\u文件获得一个文件BLOB

$file = $_FILES['filename'];
$filename = $file["tmp_name"]

$upload_file = wp_upload_bits($filename, null, $file);

if (!$upload_file['error']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent' => $parent_post_id,
        'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );

    //If you want to insert into a post or custom posttype, then make $parent_post_id = 0
    //Otherwise $parent_post_id = id of post/posttype
    $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
    if (!is_wp_error($attachment_id)) {
        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
        wp_update_attachment_metadata( $attachment_id, $attachment_data );
    //1- get the url
    $url = wp_get_attachment_url( $id );
    //2-get current logged in user ID
    $user_id = get_current_user_id();
    add_user_meta( $user_id, 'uploaded_attachments', $url );
    }else{
        //Failed with message = $attachment_id->get_error_message()

    }
}else{
    //Error : file upload failed 
}