最近模板兔给客户开发了一个同步文章的功能,就是在一个站发布文章,可以同时同步到其他多个站,需要将图片也本地化。
其中图片本地化的方法可以将以下函数添加到主题的 functions.php
文件中:
/** * 将内容中的外部图片本地化 * @param string $content 文章内容 * @return string 处理后的内容 */ function localize_content_images($content) { global $post; // 确保只在前端使用,避免在后台编辑时触发 if (is_admin() || !is_single() || empty($post->ID)) { return $content; } // 匹配所有图片标签 preg_match_all('/<img[^>]+>/i', $content, $matches); if (!empty($matches[0])) { require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); foreach ($matches[0] as $img_tag) { // 获取图片URL preg_match('/src="([^"]+)"/i', $img_tag, $img_url); if (!empty($img_url[1])) { $image_url = esc_url_raw($img_url[1]); // 检查是否是外部链接 if (strpos($image_url, home_url()) === false) { // 下载图片 $tmp = download_url($image_url); if (!is_wp_error($tmp)) { // 获取文件名 $file_array = array( 'name' => basename($image_url), 'tmp_name' => $tmp ); // 上传到媒体库 $attachment_id = media_handle_sideload($file_array, $post->ID); if (!is_wp_error($attachment_id)) { // 获取本地图片URL $local_image_url = wp_get_attachment_url($attachment_id); // 替换内容中的图片URL $content = str_replace($image_url, $local_image_url, $content); } } } } } } return $content; }
0 个评论