从前端上传多个附件和描述

时间:2012-04-26 作者:Dwayne Charrington

我正在Wordpress网站上工作,该网站有一个定制的前端提交表单,用于添加内容类型为“sketchpad”的帖子。表单有一个部分,允许您上载多个带有描述字段的图像,该字段将用作alt标记。对于我来说,从前端上传多个附件并附带说明的简单方法是什么?

当前捕获上载文件的代码如下:

// Make sure a user can edit posts (contributor level)
if (current_user_can(\'edit_posts\'))
{
    global $post;

    // If we have files
    if ( $_FILES )
    {
        // Get the upload attachment files
        $files = $_FILES[\'upload_attachment\'];

        foreach ($files[\'name\'] as $key => $value)
        {
            if ($files[\'name\'][$key])
            {
                $file = array(
                    \'name\' => $files[\'name\'][$key],
                    \'type\' => $files[\'type\'][$key],
                    \'tmp_name\' => $files[\'tmp_name\'][$key],
                    \'error\' => $files[\'error\'][$key],
                    \'size\' => $files[\'size\'][$key]
                );

                $_FILES = array("upload_attachment" => $file);

                foreach ($_FILES as $file => $array)
                {
                    $newupload = insert_attachment($file,$post->ID);
                }
            }
        }
    }
}
这是“插入附件”功能,它实际处理上载的文件并插入这些文件:

function insert_attachment($file_handler, $post_id)
{
    // check to make sure its a successful upload
    if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) __return_false();

    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( $file_handler, $post_id );

    return $attach_id;
}

1 个回复
最合适的回答,由SO网友:Dwayne Charrington 整理而成

我最终解决了这个问题。经过多次思考,我意识到附件只是分配给post\\u类型的“附件”的帖子,因此我很快发现附件有post\\u内容字段和post\\u标题字段。出于我的需要,我只需要post\\u title属性,因为我的描述很小。下面的代码对我有用。

$upload\\u id值只是从我的insert\\u attachment函数返回的附件id。

// Make sure we have an attachment ID
if ($upload_id != 0)
{
    // Insert the upload description a.k.a post title
    $post_data = array();
    $post_data[\'ID\'] = $upload_id;
    $post_data[\'post_title\'] = $file_title;
    wp_update_post($post_data);
}

结束