LoginSignup
3
5

More than 5 years have passed since last update.

wordpressでアップロード画像サイズを制限する方法

Last updated at Posted at 2015-03-02

ダッシュボードの「設定」ー>「メディア」で設定したサムネイルのサイズより小さい画像をアップしようとするとエラーメッセージを吐いて、アップロードをキャンセルさせたいときに使える。マルチアップロードの時でもOK.

キモは、WPにビルトインされているWP_Image_Editor_GDクラスを画像のサイズ判定に使うのと、wp_handle_upload_prefilter フックを使うこと。

以下のコードをfunctions.phpあたりに実装すればOK。

functions.php

require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";

add_filter("wp_handle_upload_prefilter", "cancel_upload_for_small_image");
function cancel_upload_for_small_image($file){ 
  $opt_thumbnail= array(
    "width"=> intval(get_option('thumbnail_size_w')),
    "height"=> intval(get_option('thumbnail_size_h'))
  );
  if(!preg_match("/^image\/png|jpe?g|gif$/", $file["type"])){
    //画像でないのでエラーメッセージを吐く
    $file["error"]= "this is not an image. png, or jpeg, or gif is available.";
  }

  $gd= new WP_Image_Editor_GD($file["tmp_name"]);
  $gd->load();
  $size= $gd->get_size();
  if($size["width"] < $opt_thumbnail["width"]|| $size["height"] < $opt_thumbnail["height"]){
    //ファイルサイズが小さいのでエラーメッセージを吐く
    $file["error"]= "Image must larger than {$opt_thumbnail["width"]} x {$opt_thumbnail["height"]}";
  }

  return $file;
}
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5