修复WordPress后台图片显示,使用AliyunOSS插件时

WordPress 使用 AliyunOSS 插件 如(OSS Aliyun)将图片上传到OSS服务。如果选择 不上传缩略图,使用 oss 截图功能生成缩略图的话, 后台一些地方缩略图显示会有问题,如 特色图片,和 媒体库。

使用下面的代码可以解决改问题,使用 OSS缩略图功能代替 WordPress生成的缩略图。

function yyy_wp_get_attachment_image_src($image, $attachment_id, $size, $icon)
{

    // 不是阿里云oss
    if (strpos($image[0], 'aliyuncs') === false) {
        return $image;
    }

    $attachment_url = wp_get_attachment_url($attachment_id);

    // 已经resize
    if (strpos($attachment_url, 'x-oss-process') !== false) {
        return $image;
    }

    $sizes = [
        sprintf('-%dx%d', $image[1], $image[2]),
        '-60x60',
        '-150x150',
        '-300x300'
    ];
    $image[0] = sprintf(
        '%s?x-oss-process=image/resize,m_%s,h_%d,w_%d',
        $attachment_url,
        'fill',
        $image[2],
        $image[1]
    );
    return $image;
}

add_filter('wp_get_attachment_image_src', 'yyy_wp_get_attachment_image_src', 1, 4);

function yyy_wp_prepare_attachment_for_js($post, $attachment, $meta)
{
    $full_url = $post['url'];

    $sizes = $post['sizes'];

    foreach ($sizes as $key => $size) {
        if (strpos($size['url'], 'aliyuncs') === false) {
            continue;
        }
        // 已经resize
        if (strpos($size['url'], 'x-oss-process') !== false) {
            continue;
        }

        $sizes[$key]['url'] = sprintf(
            '%s?x-oss-process=image/resize,m_%s,h_%d,w_%d',
            $full_url,
            'fill',
            $size['height'],
            $size['width']
        );
    }

    $post['sizes'] = $sizes;

    return $post;
}
add_filter('wp_prepare_attachment_for_js', 'yyy_wp_prepare_attachment_for_js', 10, 3);

1 thought on “修复WordPress后台图片显示,使用AliyunOSS插件时

Comments are closed.