Wordpress

Code tự động lưu ảnh vào host khi copy bài từ nguồn khác

Như tiêu tiêu đề thôi 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.

Ư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é

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();

Ngoài các sự dụng đoạn code này các bạn có thể sử dụng plugins, chức năng cũng tương tự

QQWorld Auto Save Images

Chúc các bạn thành công!

Huy Kira

Đam mê hóa học, ưng thi vào trường kinh tế... Đậu vào trường Sư phạm, quyết tâm đi dạy... Ra trường đi làm designer, tự học frontend, chuyển qua làm PHP, được công ty đào tạo laravel... Và hiện tại đang code react native(2015) => Fullstack ... ?? tối về viết blog... (Còn tiếp...)

View Comments

Recent Posts

Cafe với Anh Huy nghe kể chuyện hành trình fonttiengviet.com

Fonttiengviet.com là một dự án website do JKS thực hiện cho khách hàng Huy Academy.…

8 tháng ago

Giới thiệu thiết kế web Quảng Nam Web – quangnamweb.com

Chắc chắn nhiều anh em khi đọc bài viết này sẽ nghĩ tôi đang quảng…

9 tháng ago

Hướng dẫn viết widget bài viết theo chuyên mục trong wordpress

Widget trong WordPress là một công cụ mạnh mẽ cho phép bạn dễ dàng thêm…

11 tháng ago

Tạo website để viết blog với chi phí thấp nhất ai cũng làm được

Hôm nay mình sẽ hướng dẫn cho anh em cách tạo website blog cực kỳ…

11 tháng ago

WordPress có cùi bắp? Có sống tốt với nghề thiết kế website wordpress?

Sống cực tốt anh em ạ :D Sau nhiều năm gắng bó với nghề thiết…

12 tháng ago

Share mẫu website blog cá nhân cực nhẹ, giống hocwordpress.vn

Nhân dịp quay lại viết blog mình share cho anh em code mẫu website blog…

12 tháng ago