Hook into Wordpress image upload

2019-04-10 14:09发布

For my Wordpress website I want to generate programmatically and automatically an extra photo size while a user uploads a picture. I want this photo also to appear in the media library.

I wrote a little side plugin which I activate to hook into the upload action. My question is, which wp upload action I should hook into to generate this extra size of the uploaded image.

Example of getting the current upload and write the extra image entry are welcome.

Thanks!

1条回答
Emotional °昔
2楼-- · 2019-04-10 14:55

You can try 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;
}

Follow above to hook the upload action, and do some like generate extra image:

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;
}
查看更多
登录 后发表回答