Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook into Wordpress image upload

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!

like image 711
directory Avatar asked Feb 18 '15 09:02

directory


1 Answers

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;
}
like image 52
Richer Avatar answered Oct 17 '22 05:10

Richer