Code fuction tự lưu hình ảnh khi ta copy bài từ web khác về

Dưới đây là đoạn code function tự động lưu ảnh về web khi bạn copy bài viết từ website khác và dán vào trình soạn thảo của WordPress. Plugin hoặc đoạn code này sẽ tự động tải ảnh từ URL bên ngoài về thư viện Media và thay thế link ảnh trong nội dung bài viết thành link nội bộ.

Code fuction tự lưu hình ảnh khi ta copy bài từ web khác về
Code fuction tự lưu hình ảnh khi ta copy bài từ web khác về

✅ Thêm vào file functions.php của theme (hoặc tạo plugin riêng nếu bạn muốn)

//Auto Save Image In Database
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();

 

💡 Cách hoạt động:

  • Khi bạn dán nội dung từ web khác vào bài viết và nhấn “Cập nhật” hoặc “Đăng bài”, plugin sẽ:

    • Quét tất cả ảnh <img> trong bài

    • Nếu phát hiện ảnh từ nguồn ngoài (external URL), nó sẽ:

      • Tải ảnh về thư viện Media

      • Tạo attachment trong WordPress

      • Thay thế link ảnh trong nội dung thành ảnh nội bộ


🛠 Lưu ý:

  • Code phù hợp với theme con hoặc plugin tùy chỉnh.

  • Không hoạt động khi dán ảnh vào block hình ảnh, chỉ hoạt động với ảnh trong nội dung HTML.

  • Nếu ảnh có định dạng lạ, có thể cần xử lý thêm.

chúc các bạn thành công

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận