Hiển thị album hình ảnh được tạo bởi Gallery của ACF dưới dạng Masonry siêu đẹp

Để kết hợp các tính năng và hiển thị ảnh ACF Gallery dưới dạng masonry thumbnail gallery chúng ta sẽ sử dụng thư viện LightGallery.

Đoạn mã dươi sử dụng masonry để hiển thị các ảnh ACF Gallery dưới dạng lưới masonry, sau đó sử dụng LightGallery để hiển thị các ảnh trong một thumbnail gallery với các tính năng hiển thị được tùy chỉnh như thumbnail, caption, tốc độ và chế độ hiển thị ảnh. Ngoài ra, đoạn mã còn sử dụng imagesLoaded để đảm bảo rằng tất cả các hình ảnh được tải trước khi khởi tạo lưới masonry, điều này giúp tránh tình trạng hiển thị không đúng kích thước hoặc không đồng đều.

1. Chèn đoạn code sau vào vị trí bạn muốn hiển thị Album hình ảnh

<?php
	$images = get_field('gallery_cs'); // Thay 'gallery' bằng tên của trường Gallery bạn đã tạo trong ACF

	if ($images):
	?>
	<div class="justified-gallery" id="animated-thumbnails-gallery">
	  <?php foreach ($images as $image): ?>
		  <a href="<?php echo $image['url']; ?>">
			<img src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image['alt']; ?>">
		  </a>
	  <?php endforeach; ?>
	</div>
<?php endif; ?>

2. Chèn đoạn mã sau vào header

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lightgallery/dist/css/lightgallery.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/justifiedGallery@3.8.1/dist/css/justifiedGallery.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.css">

3. Chèn đoạn mã sau vào footer

<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lightgallery/dist/js/lightgallery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lg-thumbnail/dist/lg-thumbnail.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.8.1/dist/js/jquery.justifiedGallery.js"></script>

<script>
   jQuery(document).ready(function($) {
      $("#animated-thumbnails-gallery").justifiedGallery({
         captions: false,
         lastRow: "hide",
         rowHeight: 200,
         margins: 5
      }).on("jg.complete", function() {
           $("#animated-thumbnails-gallery").lightGallery({
               autoplayFirstVideo: false,
               pager: false,
               galleryId: "nature",
               plugins: [lgZoom, lgThumbnail],
               mobileSettings: {
               controls: false,
               showCloseIcon: false,
               download: false,
               rotate: false
            }
         });
      });
  });
</script>

4. Thêm đoạn css dưới đây

.justified-gallery {
margin: 0 auto;
padding: 10px;
}
.justified-gallery img {
max-width: 100%;
height: auto;
}
Chat zalo
Chat whatapp
Liên hệ chúng tôi