正文:
如何自动将 WordPress
文章中的外链图片下载到本地呢?今天汇站给大家分享一个纯代码就能实现这个功能。
将其添加到当前主题的函数模板 functions
.php
中:
attachment
= ecp_get_attachment_post
(basename
($file_path
), $wp_upload_dir
['url
'] . '/' . basename
($file_path
));
$attach_id
= wp_insert_attachment
($attachment
, ltrim
($wp_upload_dir
['subdir
'] . '/' . basename
($file_path
), '/'), 0);
$attach_data
= wp_generate_attachment_metadata
($attach_id
, $file_path
);
$ss
= wp_update_attachment_metadata
($attach_id
, $attach_data
);
}
}
}
curl_close
($ch
);
$wpdb
->update
( $wpdb
->posts
, array
('post_content
' => $post
->post_content
), array
('ID
' => $post
->ID
));
}
}
}
function
ecp_handle_ext
($file
, $type
, $file_dir
, $file_name
, $ext
) {
switch
($ext
) {
case
'tmp
':
if
(rename
($file
, str_replace
('tmp
', $type
, $file
))) {
if
('webp
' == $type
) {
return
ecp_image_convert
('webp
', 'jpeg
', $file_dir
. '/' . str_replace
('tmp
', $type
, $file_name
));
}
return
$file_dir
. '/' . str_replace
('tmp
', $type
, $file_name
);
}
case
'webp
':
if
('webp
' == $type
) {
return
ecp_image_convert
('webp
', 'jpeg
', $file
);
} else
{
if
(rename
($file
, str_replace
('webp
', $type
, $file
))) {
return
$file_dir
. '/' . str_replace
('webp
', $type
, $file_name
);
}
}
default
:
return
$file
;
}
}
function
ecp_image_convert
($from
='webp
', $to
='jpeg
', $image
) {
$im
= imagecreatefromwebp
($image
);
if
(imagejpeg
($im
, str_replace
('webp
', 'jpeg
', $image
), 100)) {
try
{
unlink
($image
);
} cat
ch
(Exception
$e
) {
$error_msg
= sprintf
('Error
removing
local
file
%s
: %s
', $image
,
$e
->getMessage
());
error_log
($error_msg
);
}
}
imagedestroy
($im
);
return
str_replace
('webp
', 'jpeg
', $image
);
}
function
ecp_get_attachment_post
($filename
, $url
) {
$file_info
= wp_check_filetype
($filename
, null
);
return
array
(
'guid
' => $url
,
'post_type
' => 'attachement
',
'post_mime_type
' => $file_info
['type
'],
'post_title
' => preg_replace
('/\.[^.]+$/', '', $filename
),
'post_content
' => '',
'post_status
' => 'inherit
'
);
}
add_action
('save_post
', 'ecp_save_post
', 120, 2);
编辑文章后,只需点击更新按钮,即可将文章中的外链图片下载到本地并替换链接。
然而,逐个编辑文章不仅繁琐而且工作量巨大。下面分享一个小技巧,可以批量下载文章中的外链图片。
该插件的代码不仅可以在正常的编辑页面点击更新按钮触发下载功能,还可以在后台的所有文章列表页面中触发下载图片功能。原理很简单,操作也很简单。
原理实现
进入 WP
后台,点击文章→所有文章,进入文章管理页面。勾选“标题”以全选当前页面的所有文章,并选择“编辑”,然后点击“应用”按钮。
请注意,不要更改批量编辑中的任何设置,只需单击“更新”即可。
这个过程将触发检查所有选定的文章,并自动下载外链图片!
转载请注明:汇站网 » 自动将 WordPress
文章中的外链图片下载到本地