使用WordPress開發(fā)主題的時候,經(jīng)常會遇到需要從前端上傳圖片的需求,乍一看,還挺麻煩的。其實WordPress已經(jīng)已經(jīng)為我們提供了非常簡單的接口,上傳附件只需要幾行代碼就能搞定。
主要工作就是引用幾個必須的文件,然后使用media_handle_upload和update_post_meta功能,我們來看一下代碼。
function insert_attachment($file_handler, $post_id, $set_thumb = 'false')
{
// 檢查附件是否上傳成功
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');
//上傳到媒體庫并返回附件的ID
$attach_id = media_handle_upload($file_handler, $post_id);
//把上傳成功的附件附加到文章
if ($set_thumb) {
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
return $attach_id;
}
如果上傳的是多個文件,需要把上面的函數(shù)稍微改一下,如下:
function insert_multiple_attachment($file_handler, $post_id)
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$files = $_FILES[ $file_handler ];
foreach ($files[ 'name' ] as $key => $value) {
if ($files[ 'name' ][ $key ]) {
$file = [
'name' => $files[ 'name' ][ $key ],
'type' => $files[ 'type' ][ $key ],
'tmp_name' => $files[ 'tmp_name' ][ $key ],
'error' => $files[ 'error' ][ $key ],
'size' => $files[ 'size' ][ $key ],
];
// 如果文件上傳不 OK ,跳過
if ($file[ 'error' ] !== UPLOAD_ERR_OK) {
continue;
}
$_FILES = [$file_handler => $file];
foreach ($_FILES as $file => $array) {
//上傳到媒體庫并返回附件的ID
$attach_id = media_handle_upload($file, $post_id);
//把上傳成功的附件附加到文章
update_post_meta($post_id, '_gallery_image_id', $attach_id);
}
}
}
}
怎么使用上面的函數(shù)
這一段是給新手準備的,高手可以直接略過,使用的時候直接把PHP的全局變量$_FILES作為函數(shù)的第一個參數(shù),需要插入的文章id作為第二個參數(shù)就可以了。
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
}
}
文件上傳成功后,在WordPress后臺看到的效果和直接在后臺插入縮略圖是一樣的。怎么樣?是不是非常簡單?如果你有更簡單的方法,歡迎在評論中提出。



求大神賜教怎么在投稿中加入上傳圖片功能,試了很多插件,都不好用,可視化編輯器可以實現(xiàn),但是上傳圖片非得注冊帳號登錄。