Xin chào các bạn hôm nay mình sẽ share đoạn code tự động lưu ảnh vào host khi copy bài từ nguồn khác. đôi lúc bạn coppy 1 bài mà quên lấy hình ảnh.
ƯU ĐIỂM: với đoạn code trên Tự động lưu tất cả hình ảnh khi copy từ nguồn khác chỉ thông qua 1 lần bấm save.
NHƯỢC ĐIỂM: code này sẽ tự động lưu nên mình ko kiểm soát được số lượng, dung lương cũng như tên của các file ảnh đó.
Các bạn copy đoạn code sau vào file functions.php trong thư mục theme bạn đang sử dụng nhé.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
class Auto_Save_Images{ function __construct(){ add_filter( 'content_save_pre',array($this,'post_save_images') ); } function post_save_images( $content ){ if( ($_POST['save'] || $_POST['publish'] )){ set_time_limit(240); global $post; $post_id=$post->ID; $preg=preg_match_all('/<img.*?src="(.*?)"/',stripslashes($content),$matches); if($preg){ foreach($matches[1] as $image_url){ if(empty($image_url)) continue; $pos=strpos($image_url,$_SERVER['HTTP_HOST']); if($pos===false){ $res=$this->save_images($image_url,$post_id); $replace=$res['url']; $content=str_replace($image_url,$replace,$content); } } } } remove_filter( 'content_save_pre', array( $this, 'post_save_images' ) ); return $content; } function save_images($image_url,$post_id){ $file=file_get_contents($image_url); $post = get_post($post_id); $posttitle = $post->post_title; $postname = sanitize_title($posttitle); $im_name = "$postname-$post_id.jpg"; $res=wp_upload_bits($im_name,'',$file); $this->insert_attachment($res['file'],$post_id); return $res; } function insert_attachment($file,$id){ $dirs=wp_upload_dir(); $filetype=wp_check_filetype($file); $attachment=array( 'guid'=>$dirs['baseurl'].'/'._wp_relative_upload_path($file), 'post_mime_type'=>$filetype['type'], 'post_title'=>preg_replace('/.[^.]+$/','',basename($file)), 'post_content'=>'', 'post_status'=>'inherit' ); $attach_id=wp_insert_attachment($attachment,$file,$id); $attach_data=wp_generate_attachment_metadata($attach_id,$file); wp_update_attachment_metadata($attach_id,$attach_data); return $attach_id; } } new Auto_Save_Images(); |
Thêm đoạn code này vào là đã tự động lưu ảnh rồi khi mình coppy từ bài viết nguồn trang khác rồi. Các bạn test xem nhé. Chúc các bạn thành công.
Còn nếu code không hoạt động trên web. Các bạn có thể sử dụng Plugin QQWorld Auto Save Images
Plugin này được auto lấy hình về bài đăng sau khi bạn bấm Save nhé.
Link download