Copy bài tự động upload ảnh wordpress

cach lay kem anh khi copy bai viet trong wordpress 549
Khi bạn Copy bài viết dự án bất động sản từ website khác về Web của mình thì phần Link ảnh là của Web người ta. Ưu điểm của việc này là bạn sẽ tiết kiệm được dung lượng và băng thông của Hosting lưu trữ Web.
Nhược điểm của nó là không tốt cho SEO, Website bạn sẽ bị Google đánh giá thấp và bạn sẽ phải phụ thuộc vào Web của người ta khi họ xoá bài viết, hình ảnh.
Thường thì các bạn tự tải ảnh về, đổi tên cho hợp lý rồi Up lên Hosting. Plugin QQWorld Auto Save Images sẽ giúp bạn giải quyết được vấn đề này.
Ngoài ra bạn có thể dùng đoạn code bên dưới vào file Functions.php
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();
Ưu điểm của code này.
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. Code ổn định không bị lỗi trên các phiên bản wordpress
Nhược điểm:
Nó 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 đó.
Để sử đụng bạn copy đoạn code sau vào file functions.php trong thư mục theme bạn đang sử dụng nhé

Trả lời