Hook into Wordpress image upload

倖福魔咒の 提交于 2019-12-21 05:23:11

问题


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:


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;
}


来源:https://stackoverflow.com/questions/28580429/hook-into-wordpress-image-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!