Custom image upload

时间:2013-04-09 作者:CBeTJlu4ok

我正在尝试为自定义帖子表单的附件设置上载。

首先,我将form 标签enctype="multipart/form-data"出于测试目的,我有两个上传表单,但将来我将只实现一个表单,并使用jQuery附加任意多个表单。

    <fieldset class="images">
        <label for="images">Front of the Bottle</label>
        <input type="file" name="image1" id="bottle_front" size="50">
    </fieldset>
    <fieldset class="images">
        <label for="images">Back of the Bottle</label>
        <input type="file" name="image2" id="bottle_rear" size="50">
    </fieldset>
在PHP中,我使用:

    if ($_FILES) {
        foreach ($_FILES as $file => $array) {
            $newupload = insert_attachment($file,$post_id);
            // $newupload returns the attachment id of the file that
            // was just uploaded. Do whatever you want with that now.
        }
    }
和在函数中。我有一些函数可以处理这个表单。

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;
 }
如果我只上传两张图片,一切都会正常,但如果我只想上传一张或一张都不想上传,我会收到错误消息my post\\u meta db:

O:8:"WP_Error":2:{s:6:"errors";a:1:{s:12:"upload_error";a:1:{i:0;s:21:"No file was uploaded.";}}s:10:"error_data";a:0:{}}
我尝试插入:if($\\u FILES[$file\\u handler][“error”]==4)\\uu return\\u false();在函数中。php但它不工作,如何告诉我的脚本我的表单是空的?

学分:took this form from here

2 个回复
最合适的回答,由SO网友:Rajeev Vyas 整理而成

可能您没有从函数中正确返回,请尝试以下操作,

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

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

SO网友:c24b

在我看来,最好简单地重用Wordpress现有的本机功能featured images 这样,您可以在自定义帖子类型中上载图像。

您可以在注册自定义帖子时启用添加选项

\'supports\' => array(\'thumbnail\')
例如许多其他有用的本机函数

结束

相关推荐

将作者从pload.php URL重定向到多站点中的主页

我想在作者访问URL时重定向他们mynetwork.com/OWNBLOG/wp-admin/upload.php 转到另一页。我该怎么做?我尝试了此代码,但收到了以下错误:“警告:无法修改标题信息-第876行/home/content/59/104129/html/wp admin/includes/template.php:1642)中/home/content/59/10412659/html/wp includes/pluggable.php中已发送的标题:”add_action( \'admin