Aleš Sýkora / November 28, 2023 / 0 comments
Swiper.js ACF Gallery slider
min read / ACF, Custom Code, Oxygen Builder, Plugins, WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: Create Swiper image slider with ACF gallery field data.
You can create a simple Image slider with Swiper.js and ACF Gallery field. Here is the quick tutorial for that.
- Create ACF Gallery field and set the ACF field to Return the Image ID
- Add Images
- Embed the Swiper.js
- Add a code for Swiper initialization
Create ACF Gallery field and add images
Go to ACF, create a field group and add field type Gallery.
Add images to the field:
Prepare the Slider
You need to embed the swiper js and css. You can use the CDN or download and add to your FTP.
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.js"></script>
I am using Advanced Scripts for that and load it from my theme folder:
Create the slider code and add it to the page or template (if you use Oxygen builder, use unwrapped code block).
<div class="swiper-container self--center">
<div class="photo-slider swiper self--center">
<div class=" swiper-wrapper">
<?php
$images = get_field('fotogalerie'); // ACF field slug
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if ($images) : ?>
<?php foreach ($images as $image_id) : ?>
<div class="swiper-slide slider-image">
<?php echo wp_get_attachment_image($image_id, $size); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</div>
Add .JS code for slider initialization (customize it how you need with Swiper API):
const swiper = new Swiper('.photo-slider.swiper', {
disableOnInteraction: false,
slidesPerView: 1,
centeredSlides: true,
loop: true,
// Responsive breakpoints
breakpoints: {
480: {
slidesPerView: 2,
spaceBetween: 15,
},
768: {
slidesPerView: 2,
spaceBetween: 25,
},
1366: {
slidesPerView: 3,
spaceBetween: 40,
},
1920: {
slidesPerView: 4,
spaceBetween: 45,
}
},
autoplay: {
delay: 1,
},
speed: 5000,
grabCursor: true,
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
Thats it, you are done.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻