很好,以下是一个简单的WordPress插件,可以将网站外部图片本地化并提供本地化选项按钮:

  1. 创建一个新的文件夹,并将其命名为“localize-images-plugin”。
  2. 在该文件夹内创建一个新的PHP文件,并将其命名为“localize-images.php”。
  3. 在“localize-images.php”文件中使用以下代码:
<?php
/*
Plugin Name: Localize Images Plugin
Plugin URI: https://www.example.com
Description: This plugin localizes external images and provides a button to choose localization.
Version: 1.0
Author: Your Name
Author URI: https://www.example.com
*/

// Add scripts and styles
function add_localize_images_scripts() {
  wp_enqueue_script('localize-images', plugin_dir_url(__FILE__) . 'localize-images.js', array('jquery'), '1.0', true);
  wp_enqueue_style('localize-images', plugin_dir_url(__FILE__) . 'localize-images.css', false, '1.0', 'all');
}
add_action('wp_enqueue_scripts', 'add_localize_images_scripts');

// Localize images function
function localize_images($content) {
  $pattern = '/<img.*?src="(.*?)"/';
  preg_match_all($pattern, $content, $matches);
  $images = $matches[1];

  foreach ($images as $image) {
    if (strpos($image, 'http') !== false) {
      $local_image = download_url($image);
      if (is_wp_error($local_image)) {
        continue;
      }
      $new_content = str_replace($image, $local_image, $content);
      wp_update_post(array(
        'ID' => get_the_ID(),
        'post_content' => $new_content
      ));
    }
  }

  return $content;
}
add_filter('the_content', 'localize_images');

// Add localize button
function add_localize_button($content) {
  $button = '<button id="localize-button">Localize Images</button>';
  return $button . $content;
}
add_filter('the_content', 'add_localize_button');

?>
  1. 在同一文件夹中创建一个名为“localize-images.js”的JavaScript文件,并使用以下代码:
jQuery(document).ready(function($) {
  $('#localize-button').click(function() {
    $('img').each(function() {
      var src = $(this).attr('src');
      if (src.indexOf('http') !== -1) {
        $(this).attr('src', localize_images_plugin_data.localize_url + '?url=' + encodeURIComponent(src));
      }
    });
  });
});
  1. 在同一文件夹中创建一个名为“localize-images.css”的CSS文件,并使用以下样式:
#localize-button {
  background: #0073aa;
  color: #fff;
  padding: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
}

#localize-button:hover {
  background: #005d86;
}
  1. 在插件文件夹中创建一个名为“index.php”的空白文件,以避免公开插件内部信息。
  2. 压缩该文件夹并将其上传到WordPress中的“wp-content/plugins/”目录中。
  3. 在WordPress后台中启用插件。

现在,您可以在WordPress中显示本地化按钮并将外部图像本地化。

现在请开发一个WordPress插件功能是可以将网站外部图片本地化并且可以有选择是否本地化的按钮

原文地址: https://www.cveoy.top/t/topic/B6Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录