前端发布-仅允许上传图像文件

时间:2019-12-25 作者:mems

如何允许用户仅上载图像文件?

作用php

// Insert Attachment
function insert_attachment($file_handler, $post_id, $setthumb=\'false\') {
    if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK){ return __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\');

//echo $attach_id = media_handle_upload($file_handler, $post_id);
$attach_id = media_handle_upload($file_handler, $post_id);

if ($setthumb == 1) update_post_meta($post_id, \'_thumbnail_id\', $attach_id);
    return $attach_id;
}
模板帖子。php

//Featured Image
if ($_FILES) {
    array_reverse($_FILES);
    $i = 0; //this will count the posts
    foreach ($_FILES as $file => $array) {
        if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
        else $set_feature = 0; //if $i!=0 we are not dealing with the first post
        $newupload = insert_attachment($file, $post_id, $set_feature);
        //echo $i++;
        }
}
需要您的帮助才能完成此操作。

1 个回复
最合适的回答,由SO网友:Chetan Vaghela 整理而成

您可以在上载到媒体之前检查上载图像的mime类型。在中添加mimeTypes$allowmimeType 您希望允许的。然后检查上载的文件mimetype$fileMimeType. 如果在允许的mimetype中找不到,则返回false。

// Insert Attachment
function insert_attachment($file_handler, $post_id, $setthumb=\'false\') {
    if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK){ return __return_false(); 
    } 

    # uploaded file type
    $fileMimeType = $_FILES[$file_handler][\'type\'];

    # allowed types
    $allowmimeType = array(
        \'png\' => \'image/png\',
        \'jpeg\' => \'image/jpeg\',
        \'gif\' => \'image/gif\',
    );

    # check if mime type type
     if(!in_array($fileMimeType,$allowmimeType) ){
       return __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\');

    //echo $attach_id = media_handle_upload($file_handler, $post_id);
    $attach_id = media_handle_upload($file_handler, $post_id);

    if ($setthumb == 1) update_post_meta($post_id, \'_thumbnail_id\', $attach_id);
        return $attach_id;
}

相关推荐

Yoast SEO过滤器钩子wpseo_sitemap_urlimages何时启动?

我正在尝试将一个简单的函数附加到Yoast SEO过滤器挂钩wpseo_sitemap_urlimages 并让函数运行,但我不能这样做。我的代码是:function tp_filter_wpseo_sitemap_urlimages($images, $post_id) { error_log(\"test message\"); return $images; } add_filter(\'wpseo_sitemap_urlimages\', \'tp_