Rất đơn giản thôi, bạn chỉ cần copy đoạn code sau vào file functions.php trong thư mục child-theme bạn đang sử dụng là ok 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();
Chúc các bạn thành công
Có thể bạn nên xem:
-
Animo – Creative & Clean Multi-Purpose WordPress T
Ngày đăng:22/03/2024Animo is a creative, clean & avant-garde WordPress theme made specifically for business, agency, creative, freelancer, blog, portfolio, photography, corporate & app or other landing page sites. Animo will give you the power to create any kind of website; the possibilities are endless! Also, how often do you get to build your site with an …
390,000đXem chi tiết
Xem thêm:
- Hướng Dẫn Chi Tiết Dreamcash Airdrop: Cách Săn Points Nhận Thưởng (Cập Nhật 2025)
- Top 10 Website Cung Cấp Code Mẫu Chuyên Nghiệp Dành Cho Các Lập Trình Viên
- Hướng dẫn đăng ký Shopify với giá chỉ 1$ cập nhật mới nhất
- Woocommerce: Những đoạn code tùy biến hay nhất
- YO là gì? Hướng dẫn Airdrop YO Token Cập Nhật Tháng 10/2025

















