問題描述
我需要一種限制作者上傳特定尺寸圖像的方法。
説我只想允許上傳至少為 400px x 400px 的圖片。如果圖像尺寸較小,作者應該收到錯誤提示,圖像太小。
有沒有可以完成這個的插件或代碼?
最佳解決方案
將此代碼添加到主題的 functions.php 文件中,並將限制最小圖像尺寸
add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');
function tc_handle_upload_prefilter($file)
{
$img=getimagesize($file['tmp_name']);
$minimum = array('width' => '640', 'height' => '480');
$width= $img[0];
$height =$img[1];
if ($width < $minimum['width'] )
return array("error"=>"Image dimensions are too small. Minimum width is {$minimum['width']}px. Uploaded image width is $width px");
elseif ($height < $minimum['height'])
return array("error"=>"Image dimensions are too small. Minimum height is {$minimum['height']}px. Uploaded image height is $height px");
else
return $file;
}
然後只需更改所需的最小尺寸數 (在我的示例中為 640 和 480)
次佳解決方案
我不喜歡重新設計一個同事的代碼。所以,這與 MaorBarazany 的答案几乎是一樣的,但檢查 mime 類型,更改 file['error']聲明並將函數命名空間更改為此 wpse 問題 ID 。
此外,僅對不是管理員的用户進行檢查。
add_action( 'admin_init', 'wpse_28359_block_authors_from_uploading_small_images' );
function wpse_28359_block_authors_from_uploading_small_images()
{
if( !current_user_can( 'administrator') )
add_filter( 'wp_handle_upload_prefilter', 'wpse_28359_block_small_images_upload' );
}
function wpse_28359_block_small_images_upload( $file )
{
// Mime type with dimensions, check to exit earlier
$mimes = array( 'image/jpeg', 'image/png', 'image/gif' );
if( !in_array( $file['type'], $mimes ) )
return $file;
$img = getimagesize( $file['tmp_name'] );
$minimum = array( 'width' => 640, 'height' => 480 );
if ( $img[0] < $minimum['width'] )
$file['error'] =
'Image too small. Minimum width is '
. $minimum['width']
. 'px. Uploaded image width is '
. $img[0] . 'px';
elseif ( $img[1] < $minimum['height'] )
$file['error'] =
'Image too small. Minimum height is '
. $minimum['height']
. 'px. Uploaded image height is '
. $img[1] . 'px';
return $file;
}
鈎的結果:
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
