워드프레스 고급 강의 - swiper

슬라이드 배너 템플릿 제작하기(swiper.js) – 워드프레스 강좌

이번에는 워드프레스에서 슬라이드 배너를 만드는 방법을 알려 드릴게요. swiper.js를 사용해볼 것이고, 실제 글 데이터를 넣어서 사용하는 방법을 배워볼게요.

파일 생성

먼저, 필요한 파일들을 생성합니다. 예를 들어, templates 폴더를 만들어 carousel-banner.phpcontent-work-slide.php 파일을 생성합니다.

1. carousel-banner.php

캐로셀 배너의 메인 코드를 포함하는 파일입니다.


<div class="main-swiper">
    <!-- Additional required wrapper -->
    <div class="swiper-wrapper">

        <!-- 배열에 대한 정의 -->
        <?php
            $hero = new WP_Query(
                array(
                    'posts_per_page' => 4,
                    // 'post_type' => 'work',
                )
            );
        ?>
        <!-- while문 : 해당 배열 안에 포스트를 반복해서 불러오기 -->
        <?php while ($hero->have_posts()) : $hero->the_post(); ?>
            <!-- Start : 이 안에 코드 형식으로 출력 -->
            <div class="swiper-slide">
                <?php get_template_part('content-work-slide'); ?>
            </div>
            <!-- End : 이 안에 코드 형식으로 출력 -->
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    </div>

    <!-- If we need pagination -->
    <div class="swiper-pagination"></div>

    <!-- If we need navigation buttons -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
</div>

2. content-work-slide.php

슬라이드 콘텐츠를 정의하는 파일입니다.


<a href="<?php echo esc_url(get_permalink()); ?>">
    <div class="entry-thumbnail">
        <?php the_post_thumbnail('post-thumbnail-img'); ?>
    </div>
    <div class="entry-text-wrap">
        <h1 class="entry-title"><?php the_title(); ?></h1>
    </div>
</a>

3. home.js (또는 common.js)

Swiper.js 설정을 포함하는 JavaScript 파일입니다. 다른 곳에서도 사용하려면 common.js에 추가합니다.

const mainSwiper = new Swiper('.main-swiper', {
    // If we need pagination
    pagination: {
        el: '.swiper-pagination',
    },
    // Navigation arrows
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
    // And if we need scrollbar
    // scrollbar: {
    //     el: '.swiper-scrollbar',
    // },
});

해당 템플릿 불러오기

워드프레스 템플릿 파일에서 get_template_part 함수를 사용하여 캐로셀 배너를 쉽게 불러올 수 있습니다.

<?php get_template_part('templates/carousel-banner'); ?>

이렇게 하면 여러 페이지에서 동일한 캐로셀 배너를 사용하더라도 코드를 반복적으로 작성할 필요 없이 쉽게 재사용할 수 있습니다.

또한, 각각의 컴포넌트를 별도의 파일로 분리하여 관리하기 때문에 유지보수가 용이해집니다.