upload image only

时间:2014-09-28 作者:LET ME

我从前端创建post页面,并为uplaod功能图像添加代码。我使用此代码

    if (!function_exists(\'wp_generate_attachment_metadata\')){
            require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
            require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
            require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
        }
         if ($_FILES) {
            foreach ($_FILES as $file => $array) {
                if ($_FILES[$file][\'error\'] !== UPLOAD_ERR_OK) $error_array[]=\'STOP\';
                $attach_id = media_handle_upload( $file, $post_id );
            }   
        }
        if ($attach_id > 0){
            //and if you want to set that image as Post  then use:
            update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
        }
这是工作。但我只想上传图片

我该怎么做?

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

我编辑了代码

    if (!function_exists(\'wp_generate_attachment_metadata\')){
            require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
            require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
            require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
        }
         if ($_FILES) {
            foreach ($_FILES as $file => $array) {
            $mime = $_FILES[$file][\'type\'];
            $filesize = $_FILES[$file][\'size\'];
            $maxsizef = 524288;
            if($filesize > $maxsizef) $error_array[] = \'error size, max file size = 500 KB\';
            if(($mime != \'image/jpeg\') && ($mime != \'image/jpg\') && ($mime != \'image/png\')) $error_array[] =\'error type , please upload: jpg, jpeg, png\';
                $attach_id = media_handle_upload( $file, $post_id );
            }   
        }
        if ($attach_id > 0){
            //and if you want to set that image as Post  then use:
            update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
        }
这是工作。

SO网友:adrian7

我想您的问题的答案在您使用的代码中有很好的记录:

 //and if you want to set that image as Post  then use:
 update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
因此,您只需对以下行进行注释:update_post_meta($post_id,\'_thumbnail_id\',$attach_id);

结束