You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无插件实现S3存储桶图片接入WordPress媒体库(Docker环境)

问题描述

我花了一周时间尝试将AWS S3与Docker容器中运行的WordPress站点对接。原本打算使用专用插件,但所有插件均提示wp-config存在AWS S3配置冲突,只好自行开发。目前已编写PHP页面,可查看、上传、删除S3存储桶内的图片,也能将S3图片URL存入WordPress数据库使其在媒体库中显示,但页面设置的媒体选择器中无法看到这些图片。

自定义模板页面(S3 Image Gallery)

<?php
/*
Template Name: S3 Image Gallery
*/

// Include the AWS SDK for PHP
include realpath(dirname(__FILE__)) .'/aws/aws-autoloader.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// Replace these with your AWS credentials and bucket name
$aws_access_key = 'key';
$aws_secret_key = 'secret';
$bucket_name = 'bucketname';
$aws_region = 'region';

// Instantiate the S3Client
$s3_client = new S3Client([
    'version' => 'latest',
    'region' => $aws_region,
    'credentials' => [
        'key' => $aws_access_key,
        'secret' => $aws_secret_key,
    ],
]);

// Function to get the list of objects in the S3 bucket
function get_s3_objects() {
    global $s3_client, $bucket_name;
    try {
        $objects = $s3_client->listObjects([
            'Bucket' => $bucket_name,
        ]);

        return $objects['Contents'];
    } catch (S3Exception $e) {
        // Handle the exception, e.g., display an error message
        return [];
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>S3 Bucket Gallery</title>
    <style>
        /* Add CSS styles for the gallery layout */
        .gallery-carousel {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
        }
        .gallery-item {
            width: 140px;
            height: 140px;
            margin: 5px;
            overflow: hidden;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .gallery-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        /* Add CSS styles for the carousel */
        .slick-slide {
            margin: 0 5px;
        }
    </style>
    <!-- Add Slick Carousel CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/>
</head>
<body>
    <!-- Wrapper for the carousel -->
    <div class="gallery-carousel">
        <?php
        // Get the list of objects in the S3 bucket
        $objects = get_s3_objects();

        // Loop through the objects and display images in the gallery
        foreach ($objects as $object) {
            $image_url = $s3_client->getObjectUrl($bucket_name, $object['Key']);
            echo '<div class="gallery-item"><img src="' . $image_url . '" alt="Image"></div>';
        }
        ?>
    </div>

    <!-- Form to upload new image -->
    <div>
        <h2>Upload New Image</h2>
        <form action="<?php echo get_permalink(); ?>" method="post" enctype="multipart/form-data">
            <input type="file" name="image_file">
            <input type="submit" value="Upload">
        </form>
    </div>

    <!-- Add Slick Carousel JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
    <script>
        // Initialize the Slick Carousel on the gallery-carousel element
        $(document).ready(function() {
            $('.gallery-carousel').slick({
                infinite: true,
                slidesToShow: 4, // Set the number of slides to show at once
                slidesToScroll: 1,
                prevArrow: '<button type="button" class="slick-prev">Previous</button>',
                nextArrow: '<button type="button" class="slick-next">Next</button>',
            });
        });
    </script>
</body>
</html>

<?php
// Function to upload an image to the S3 bucket
function upload_to_s3($file) {
    global $s3_client, $bucket_name;
    try {
        $object_key = basename($file['name']);
        $s3_client->putObject([
            'Bucket' => $bucket_name,
            'Key' => $object_key,
            'SourceFile' => $file['tmp_name'],
        ]);

        // Get the URL of the uploaded image
        $image_url = $s3_client->getObjectUrl($bucket_name, $object_key);
        return $image_url;
    } catch (S3Exception $e) {
        // Handle the exception, e.g., display an error message
        return false;
    }
}

// Handle image upload if a file is submitted
if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
    $uploaded_url = upload_to_s3($_FILES['image_file']);
    if ($uploaded_url) {
        // Image uploaded successfully, display the URL
        echo '<p>Image uploaded successfully. URL: <a href="' . $uploaded_url . '">' . $uploaded_url . '</a></p>';
    } else {
        // Image upload failed, display an error message
        echo '<p>Image upload failed.</p>';
    }
}

// Function to delete an image from the S3 bucket
function delete_from_s3($object_key) {
    global $s3_client, $bucket_name;
    try {
        $s3_client->deleteObject([
            'Bucket' => $bucket_name,
            'Key' => $object_key,
        ]);
    } catch (S3Exception $e) {
        // Handle the exception, e.g., display an error message
    }
}

// Handle image upload if a file is submitted
if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
    upload_to_s3($_FILES['image_file']);
}

// Handle image deletion if a key is passed via GET parameter
if (isset($_GET['delete'])) {
    delete_from_s3($_GET['delete']);
}
?>

functions.php中的数据库插入函数

function insert_s3_image_to_db($image_url) {
    // Check if the file exists on the S3 bucket
    if (get_headers($image_url)[0] === 'HTTP/1.1 200 OK') {
        // Fetch the title from the S3 URL
        $title = sanitize_file_name(basename(parse_url($image_url, PHP_URL_PATH)));

        // Get the file size using the S3 URL headers
        $headers = get_headers($image_url, true);
        $file_size = isset($headers['Content-Length']) ? (int) $headers['Content-Length'] : 0;

        // Prepare the attachment data
        $attachment_data = array(
            'guid'           => $image_url, // Set the S3 URL as the GUID
            'post_mime_type' => 'image', // You can also get the mime type from S3 if available
            'post_title'     => $title, // Use the title as the file name
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        // Set a custom attachment ID to prevent WordPress from modifying the GUID
        $custom_attachment_id = time(); // Use any unique value for the attachment ID

        // Insert the attachment into the WordPress database
        $attachment_id = wp_insert_attachment($attachment_data, '', $custom_attachment_id);

        if (!is_wp_error($attachment_id)) {
            // Generate the metadata for the attachment
            require_once ABSPATH . 'wp-admin/includes/image.php';
            $attachment_metadata = wp_generate_attachment_metadata($attachment_id, $image_url);
            $attachment_metadata['file_size'] = $file_size;
            list($width, $height) = getimagesize($image_url);
            $attachment_metadata['width'] = $width;
            $attachment_metadata['height'] = $height;
            wp_update_attachment_metadata($attachment_id, $attachment_metadata);
        }
    }
}

内容的提问来源于stack exchange,提问作者utkuyceng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:32:13