

Code functions lưu hình ảnh tự động ở bài viết về host khi copy từ trang khác
Giới thiệu
Đoạn code này cho phép người dùng copy bài viết từ trang khác về, khi bạn nhấn lưu bài viết thì toàn bộ hình ảnh trong bài viết sẽ được lưu vào host của bạn, code cũng đổi tên cả tên hình ảnh theo tên của bài đăng.
Code tự động lưu hình ảnh vào host
class fox_save_images_hots{
function __construct(){
add_filter( 'content_save_pre',array($this,'fox_post_save_images') ); }
function fox_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->fox_fill_save_images($image_url,$post_id);
$replace=$res['url'];
$content=str_replace($image_url,$replace,$content);}}}}
remove_filter( 'content_save_pre', array( $this, 'fox_post_save_images' ) );
return $content;}
function fox_fill_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->fox_insert_attachment($res['file'],$post_id);
return $res;}
function fox_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 fox_save_images_hots();
Bạn sao chép toàn bộ code trên dán vào file functions.php trong thư mục theme mà bạn đang sử dụng