星期二 , 15 4 月 2025

函数逻辑优化

<?php
$post_id = get_the_ID();
$gallery = get_post_meta($post_id, '_product_gallery', true);

// Ensure $gallery is an array (handle JSON string case)
if (is_string($gallery)) {
    $decoded_gallery = json_decode($gallery, true);
    $thumbs = is_array($decoded_gallery) ? $decoded_gallery : [];
} else {
    $thumbs = is_array($gallery) ? $gallery : [];
}

// Fallback to Carbon Fields if no valid images found
if (empty($thumbs)) {
    $thumbs = carbon_get_post_meta($post_id, 'crb_media_gallery');
}

// Display thumbnails only if available
if (!empty($thumbs)) :
    foreach ($thumbs as $index => $thumb) {
        $classes = ['swiper-slide'];
        if ($index === 0) $classes[] = 'swiper-slide-active';
        if ($index === 1) $classes[] = 'swiper-slide-next';

        // Determine the image URL (Handle JSON structure variations)
        $thumb_url = isset($thumb['url']) ? $thumb['url'] : wp_get_attachment_image_url($thumb, 'full');

        if ($thumb_url): ?>
            <div class="<?php echo implode(' ', $classes); ?>" style="width: 83px; margin-right: 5px;">
                <a data-zoom-id="zoomview" href="<?php echo esc_url($thumb_url); ?>" 
                   class="mz-thumb<?php echo $index === 0 ? '-selected' : ''; ?>">
                    <img src="<?php echo esc_url($thumb_url); ?>" 
                         alt="<?php echo esc_attr(get_the_title()); ?>" 
                         class="img-fluid m-auto">
                </a>
            </div>
        <?php 
        endif;
    }
endif;
?>