星期三 , 22 1 月 2025

自定义图片收集框架适用方法

定义函数

function get_image_collection($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }

    $image_ids = get_post_meta($post_id, 'image_collection', true);

    if (!$image_ids || !is_array($image_ids)) {
        return array();
    }

    $images = array();
    foreach ($image_ids as $image_id) {
        $image = array(
            'id' => $image_id,
            'url' => wp_get_attachment_url($image_id),
            'alt' => get_post_meta($image_id, '_wp_attachment_image_alt', true),
            'caption' => wp_get_attachment_caption($image_id),
        );
        $images[] = $image;
    }

    return $images;
}

创建图片展示模板 single-post 模板

<?php
get_header();

while ( have_posts() ) :
    the_post();
    ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <header class="entry-header">
            <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
        </header>

        <div class="entry-content">
            <?php
            the_content();

            $images = get_image_collection();
            if (!empty($images)) :
                ?>
                <div class="image-collection-gallery">
                    <?php foreach ($images as $image) : ?>
                        <figure class="image-collection-item">
                            <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>">
                            <?php if (!empty($image['caption'])) : ?>
                                <figcaption><?php echo esc_html($image['caption']); ?></figcaption>
                            <?php endif; ?>
                        </figure>
                    <?php endforeach; ?>
                </div>
                <?php
            endif;
            ?>
        </div>
    </article>
    <?php
endwhile;

get_footer();
?>

添加必要css

.image-collection-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.image-collection-item {
    margin: 0;
}

.image-collection-item img {
    width: 100%;
    height: auto;
    display: block;
}

.image-collection-item figcaption {
    margin-top: 10px;
    text-align: center;
    font-style: italic;
}

在其他地方展示

$images = get_image_collection(123); // Replace 123 with the actual post ID
if (!empty($images)) {
    echo '<div class="image-collection-gallery">';
    foreach ($images as $image) {
        echo '<figure class="image-collection-item">';
        echo '<img src="' . esc_url($image['url']) . '" alt="' . esc_attr($image['alt']) . '">';
        if (!empty($image['caption'])) {
            echo '<figcaption>' . esc_html($image['caption']) . '</figcaption>';
        }
        echo '</figure>';
    }
    echo '</div>';
}