允许用户从前端将图片上传到帖子

时间:2014-04-12 作者:M P

我想让登录用户(Wordpress)能够从前端提交帖子(以及其他数据)。

我的表单工作得很好,我添加了自定义帖子元数据,这些元数据稍后会显示在自定义帖子页面上。

我补充道enctype="multipart/form-data" 形成标签。

将此代码添加到函数中。php:

function insert_attachment($file_handler,$post_id,$setthumb=\'false\') {
    // 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 );
    if ($setthumb) update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
    return $attach_id;
}
并将其发送到自定义贴子页面(其中前端表单为):

if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$pid);
    }
};
在这段php代码之后,我有以下代码来创建帖子:

$post_information = array(
\'post_title\' => wp_strip_all_tags( $_POST[\'title\']),
\'post_content\' => $_POST[\'content\'],
\'post_category\' => array($_POST[\'category\']),
\'post_type\' => \'post\',
\'post_status\' => \'pending\'
);

$post_information = wp_insert_post($post_information);
add_post_meta($post_information, \'custom1\', $_POST[\'custom1\']);
add_post_meta($post_information, \'custom2\', $_POST[\'custom2\']);
add_post_meta($post_information, \'custom3\', $_POST[\'custom3\']);
现在,将帖子数据毫无问题地添加到新帖子中,并上传图像。我用以下内容上载图像:

<input type="file" tabindex="3" name="custom-upload1" id="custom-upload2" />
<input type="file" tabindex="3" name="custom-upload2" id="custom-upload2" />
<input type="file" tabindex="3" name="custom-upload3" id="custom-upload3" />
现在,我需要找到一种方法来保存和显示创建的自定义帖子上的图像。我在考虑这两种选择:

将上载的图像URL保存在自定义字段中

有没有办法这样省钱:

add_post_meta($post_information, \'imageURL\', $_POST[\'imageURL\']);
但我不知道如何将image URL变量传递给“imageURL”。

有没有其他选择?

1 个回复
SO网友:Dharmang

wp_insert_attachment 返回结果post_ID 在posts表中创建的附件记录的个数,因此您需要使用在post元表中添加这些ID(多个)update_post_meta 如下代码所示:

$attchmentIds = array();
if ($_FILES) {
    foreach ($_FILES as $file => $array) {
        $newupload = insert_attachment($file,$pid);
        $attchmentIds[] = $newupload;
    }
};
/*The following code will go after wp_insert_post call*/
update_post_meta($post_information, \'_post_custom_attachments\', $attchmentIds);
现在,一旦完成此操作,当您想要在单个页面上显示帖子上的图像时,您将需要从post meta字段获取这些附件ID并使用wp_get_attachment_url 功能:

/*The_Loop*/
$attachmentIds = get_post_meta(get_the_ID(), \'_post_custom_attachments\');

foreach($attachmentIds as $attachmentId) {
    echo wp_get_attachment_url( $attachmentId );
    //outputs something like http://example.net/wp-content/uploads/filename
}
参考链接:

http://codex.wordpress.org/Function_Reference/wp_insert_attachmenthttp://codex.wordpress.org/Function_Reference/wp_get_attachment_url

结束