挂钩到 Wordpress 图片上传

dir*_*ory 6 php wordpress hook image

对于我的 Wordpress 网站,我想在用户上传图片时以编程方式自动生成额外的照片大小。我希望这张照片也出现在媒体库中。

我写了一个小插件,我激活它以挂钩上传操作。我的问题是,我应该使用哪个 wp 上传操作来生成这个额外大小的上传图像。

欢迎使用获取当前上传和写入额外图像条目的示例。

谢谢!

小智 5

你可以试试 wp_handle_upload_prefilter:

add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
    $file['name'] = 'wordpress-is-awesome-' . $file['name'];
    return $file;
}
Run Code Online (Sandbox Code Playgroud)

按照上面的方法钩住上传操作,并执行一些类似生成额外图像的操作:

function generate_image($src_file, $dst_file) {
     $src_img = imagecreatefromgif($src_file);
     $w = imagesx($src_img);
     $h = imagesy($src_img);

     $new_width = 520;
     $new_height = floor($new_width * $h / $w);

     if(function_exists("imagecopyresampled")){
         $new_img = imagecreatetruecolor($new_width , $new_height);
         imagealphablending($new_img, false);
         imagecopyresampled($new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
     } else {
         $new_img = imagecreate($new_width , $new_height);
         imagealphablending($new_img, false);
         imagecopyresized($new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
     }
     imagesavealpha($new_img, true);    
     imagejpeg($new_img, $dst_file);

     imageDestroy($src_img);
     imageDestroy($new_img);

     return $dst_file;
}
Run Code Online (Sandbox Code Playgroud)