在Wordpress中将图像数组保存给用户



是否可以将图像数组保存给用户?

我已经创建了一个表单,并且正在保存部分。

我已经有这段代码了:

update_user_meta($user->ID, 'gallery', $_POST['gallery_images']);

gallery_images包含表单中的输入图像数组。

我知道这是行不通的。是否可以在用户中保存图像数组?如果可能,如何?

附言。我使用的是最新版本的wordpress。

(修订后的答案(

正如另一个答案的评论中所指出的,您可以使用media_handle_upload()上传图像,但由于该功能仅支持次上传,那么对于多次上传,您可以像这样设置临时$_FILES项:

// Load upload-related and other required functions.
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$post_id = 0;   // set to the proper post ID, if attaching to a post
$uploaded = []; // attachment IDs
foreach ( $_FILES['gallery_images']['tmp_name'] as $key => $file ) {
    // Set a temporary $_FILES item.
    $_FILES['_tmp_gallery_image'] = [
        'name'     => $_FILES['gallery_images']['name'][ $key ],
        'type'     => $_FILES['gallery_images']['type'][ $key ],
        'size'     => $_FILES['gallery_images']['size'][ $key ],
        'tmp_name' => $file,
        'error'    => $_FILES['gallery_images']['error'][ $key ],
    ];
    // Upload the file/image.
    $att_id = media_handle_upload( '_tmp_gallery_image', $post_id );
    if ( ! is_wp_error( $att_id ) ) {
        $uploaded[] = $att_id;
    }
}
unset( $_FILES['_tmp_gallery_image'] );
// Save the attachment IDs.
$user = wp_get_current_user();
update_user_meta( $user->ID, 'gallery', $uploaded );

我正在保存附件ID,但是当然,如果您宁愿保存图像URL等,这取决于您。

PS:您可以在此处查看原始答案,看看如何使用media_handle_sideload()上传图像。(它运行良好,但与其通过包装器(函数(,我们应该只调用media_handle_upload(),除非您正在"上传"外部/远程图像/文件。对不起这个答案..:)

您可以序列化数据,并在需要时取消序列化它。

update_user_meta($user->ID, 'gallery', serialize($_POST['gallery_images']));

序列 化:https://www.php.net/manual/fr/function.serialize.php

最新更新