Code tự động lưu hình ảnh khi copy nội dung từ website khác wordpress

Wordpress

Chào mọi người. hôm nay mình chia sẻ đến các bạn chuyên đi copy content từ website khác, mà lười save từng hình ảnh ? .
Khi bạn Copy bài viết từ các nguồn khác nhau về Web của mình thì phần Link ảnh vẫn ở Web gốc. Điều này có ưu điểm là bạn sẽ tiết kiệm dung lượng và băng thông cho Hosting. Nhược điểm của nó là không tốt cho SEO và bạn sẽ phải phụ thuộc vào web gốc. Nếu nó bị die thì web của bạn bị ảnh hưởng load chậm hoặc không load được ảnh.

Bạn thường kéo trên xuống bài viết của họ hay coppy từng đoạn, rồi coppy hình ? Với code này bạn chỉ cần kéo từ trên xuống paste vào web của bạn xong đó lưu lại. Code sẽ tự tải ảnh bạn đã coppy về web của bạn với đường dẫn web bạn.

Video hướng dẫn ở trên.

Copy đoạn code bên dưới vào file funtions.php

[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();
[/php]

Like nếu thấy bài viết hữu ích với bạn, mình sẽ cập nhật thêm nhiều bài viết hay cho a e!

Giới thiệu với bạn Chợ WordPress chuyên bán theme, plugin chính hãng, đây là chợ rất uy tín, các bạn có thể mua ở đây nhé:

Link: https://chowordpress.com/

back top