也想出现在这里?联系我们

纯代码实现 WordPress 支持 WebP 格式图片上传

2024.03.09 wordpress教程
  • 文章介绍
  • 升级版本
  • 评价&建议

要在WordPress中支持WebP格式的图片上传,您可以使用以下步骤纯代码实现:

  1. 安装WebP支持插件:

    首先,您需要安装并激活一个能够在WordPress中支持WebP格式的插件。在代码中,您可以使用以下代码来安装插件:

    function install_webp_support_plugin() {
       $plugin_slug = 'webpexpress';
       $plugin_path = ABSPATH . 'wpcontent/plugins/' . $plugin_slug;
    
       // Check if the plugin is not already installed
       if (!is_dir($plugin_path)) {
           $download_url = 'https://downloads.wordpress.org/plugin/' . $plugin_slug . '.lateststable.zip';
    
           // Use WordPress functions to download and install the plugin
           include_once ABSPATH . 'wpadmin/includes/file.php';
           WP_Filesystem();
    
           $tmp_dir = get_temp_dir();
           $zip_file = $tmp_dir . '/' . $plugin_slug . '.zip';
    
           // Download the plugin zip file
           $response = wp_safe_remote_get($download_url);
           if (is_wp_error($response)) {
               return false;
           }
    
           // Save the zip file to the temporary directory
           wp_safe_remote_fopen($zip_file, 'w', $response);
    
           // Unzip the plugin to the plugins directory
           WP_Filesystem();
           unzip_file($zip_file, ABSPATH . 'wpcontent/plugins/');
       }
    }
    add_action('init', 'install_webp_support_plugin');

    这个代码会在WordPress初始化时检查是否已经安装了WebP支持插件(WebP Express)。如果没有安装,它将从WordPress官方插件仓库下载并安装。

  2. 启用WebP支持插件:

    确保您已经在WordPress后台启用了WebP支持插件。这通常需要手动完成,因为代码不能自动启用插件。

  3. 测试WebP图片上传:

    现在,您应该能够在WordPress中上传WebP格式的图片。在“媒体库”中,您可以尝试上传一个WebP图片,然后在文章或页面中使用它。

请注意,WebP支持插件可能会更新,因此请确保检查并使用最新版本的插件以获取最佳性能和安全性。此外,上述代码只是为了演示如何在代码中自动安装插件,您也可以手动下载并安装WebP Express插件。确保您了解您的站点的需求和安全性,以选择适合的插件和方法。

有用0
  • 2024.03.09初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧