gpt4 book ai didi

php - Wordpress 中的前端媒体上传

转载 作者:行者123 更新时间:2023-11-30 09:01:14 26 4
gpt4 key购买 nike

我需要一些帮助! :)

我想做的是让用户从前端创建帖子。带有一个预览窗口,显示帖子发布后的样子。这我已经做到了。现在我试图让用户将图像直接上传到媒体库中。一旦用户选择了带有以下代码的文件,就需要进行此上传:

 <form method="post" action="#" enctype="multipart/form-data" >
<input type="file" name="featured_image">
</form>

我不想加载任何页面,有没有一种方法可以在不使用提交按钮的情况下获取文件?另外我如何处理实际的文件上传,我的谷歌技能找到了这个功能:

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;
}

但是这个函数 Hook 了上传到一个帖子,我只是想让它直接进入图书馆而不是连接到一个帖子。我还假设 $file_handler 是表单的名称?我还假设 $_FILES 不存在,除非用户点击了提交按钮。

我很可能离题太远了,胡说八道。因此,将不胜感激任何帮助。有可用的 WP 专家吗? :D

最佳答案

我遇到了同样的问题。 Wordpress 文档有助于: http://codex.wordpress.org/Function_Reference/wp_handle_uploadhttp://codex.wordpress.org/Function_Reference/wp_insert_attachment

更新:$key 是 type="file"的名称

我只是添加了guid值,因为它似乎没有添加(也许有更好的方法,然后包括admin.php:

        require_once(ABSPATH . 'wp-admin/includes/admin.php');
// step one upload file to server
$file_return = wp_handle_upload($_FILES[$key], array('test_form' => false));

if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
echo 'not working again :(';
}
else {
/**
* See http://codex.wordpress.org/Function_Reference/wp_insert_attachment
*
*/
$filename = $file_return['file'];

$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attach_id = wp_insert_attachment( $attachment, $file_return['url'] );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

}


}

关于php - Wordpress 中的前端媒体上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9160979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com