[section] portfolio – 3A

페이지 하단에 포트폴리오 내용을 추가해서 볼 수 있는 버튼을 추가 하고 버튼 클릭시 포트폴리오 들이 추가 되는 기능을 구현해 보겠습니다.

  • jQuery: ajax를 이용한 페이지 로딩 및 추가

포트폴리오 하단에 버튼을 추가 합니다.

index.php
<div class="row">
	<div class="col-12 text-center mt-5">
		<button id="btn-load-more" class="zeein-button zeein-button-dark" data-security="<?php echo wp_create_nonce('load_more_portfolio'); ?>">VIEW MORE PORTFOLIO</button>
	</div><!-- .col-12 -->
</div><!-- .row -->

추가된 버튼이 white 배경에서는 보이지 않아 zeein-button-dark 클래스를 추가 했고 관련해서 main.css 스타일도 일부 내용 추가 합니다.

main.css
    .zeein-button.zeein-button-dark {
        color: black;
        border-color: #FBD04B;
    }

#btn-load-more 버튼 클릭시 ajax 호출 하는 부분을 custom.js 파일에 추가 합니다.

custom.js
    // load more
    var defaultPageNum = 2;
    $('#btn-load-more').on('click', function(e){
        var $content = $('.ajax-portfolio');
        var $loader = $('#btn-load-more');
        var security = $loader.data('security');
        var sendData = {
            action: 'load_portfolio_by_ajax',
            query_vars: frontend_ajax_object.query_vars,
            paged: defaultPageNum,
            security : security,
        }
        $.ajax({
            type: 'post',
            url: frontend_ajax_object.ajaxurl,
            data: sendData,
            beforeSend: function() {
               $loader.html('LOADING PORTFOLIO..');
            },
            success: function(data) {
                var $data = $(data);
                if ($data.length) {
                    var $newElements = $data.css({opacity: 0});
                    $grid.append($newElements).imagesLoaded(function() {
                        $grid.masonry('appended', $data, true);
                    });
                    $newElements.animate({opacity: 1});
                    initMagnific();
                    $loader.html('VIEW MORE PORTFOLIO');
                } else {
                    $loader.html('NO MORE PORTFOLIO');
                }
                defaultPageNum++;
            },
            error : function (jqXHR, textStatus, errorThrown) {
				$loader.html($.parseJSON(jqXHR.responseText) + ' :: ' + textStatus + ' :: ' + errorThrown);
                console.log(jqXHR);
            }
        });

        return false;
    });

이제부터 조금 복잡한 부분이니 잘 따라 하시기 바랍니다.

복잡해 지는 이유는 index.php 파일에서 반복적으로 사용되는 포트폴리오 부분이 functions.php 파일에서도 반복해서 사용해야 하는데 만약 수정할 일이 발생하면 매번 index.php 파일과 functoins.php 파일을 같이 수정해야 하고 관리할대 여간 불편하지가 않습니다.

그래서 반복되는 부분을 템플릿화 해서 index.phpfunctions.php 파일에서 불러서 사용하도록 전체적으로 수정 작업을 하겠습니다.

index.php
                                    $img = wp_get_attachment_image_src( get_post_thumbnail_id( $the_query->ID ), 'large' );
                                    $fullImg = wp_get_attachment_image_src( get_post_thumbnail_id( $the_query->ID ), 'full' ); 
                            ?>
                                <div class="grid-item">
                                    <div class="portfolio-wrap">
                                        <figure>
                                            <img src="<?php echo $img[0]; ?>" alt="portfolio">
                                            <div class="over-wrap-bg">
                                                <div class="over-wrap">
                                                    <?php
                                                        $posts = get_field('crew');
                                                        if ( $posts ) :?>
                                                        <ul class="crew-wrap">
                                                            <?php foreach( $posts as $p): ?>
                                                                <?php
                                                                $img_crew = wp_get_attachment_image_src( get_post_thumbnail_id( $p->ID ), 'thumbnail' );
                                                                ?>
                                                                <li><img src="<?php echo $img_crew[0]; ?>" alt="crew"></li>
                                                            <?php endforeach; ?>
                                                        </ul>
                                                    <?php endif; ?>
                                                    <div class="meta-wrap">
                                                    <?php
                                                    if ( get_the_terms( $the_query->ID, 'portfolio_tag' ) ) {
                                                        echo '
                                                        <div class="tag-wrap"><i class="demo-icon icon-tag"></i> ' . strip_tags(get_the_term_list($the_query->ID, 'portfolio_tag', '', ' , ')) . '</div>';
                                                    }
                                                    if ( $location = get_field('location') ) {
                                                        echo '<div class="location-wrap"><i class="demo-icon icon-location-circled"></i> '.$location.'</div>';
                                                    }

                                                    ?>
                                                        <a class="show-popup" href="<?php echo $fullImg[0]; ?>">Detail Image</a>
                                                    </div>
                                                </div><!-- .over-wrap -->
                                            </div><!-- .over-wrap-bg -->
                                        </figure>
                                        <div class="desc-wrap">
                                            <?php
                                            the_title('<h4 class="title">', '</h4>');
                                            
                                            if ( $getTheContent = get_the_content() ) :
                                                echo '
                                                <hr>
                                                <div class="content-wrap">
                                                '.$getTheContent.'
                                                </div>';
                                            endif;
                                            ?>
                                        </div>
                                    </div>
                                </div><!-- .grid-item -->

기존의 내용중 위의 부분을 잘라내서 테마 폴더에 zeein-yellow > template-parts 폴더를 만들고 폴더 안에 content-portfolio.php 파일을 새로 만든 뒤 잘라낸 부분을 붙혀 넣기 합니다.

content-portfolio.php
<?php
global $the_query;
$img = wp_get_attachment_image_src( get_post_thumbnail_id( $the_query->ID ), 'large' );
$fullImg = wp_get_attachment_image_src( get_post_thumbnail_id( $the_query->ID ), 'full' ); 
?>
<div class="grid-item">
    <div class="portfolio-wrap">
        <figure>
            <img src="<?php echo $img[0]; ?>" alt="portfolio">
            <div class="over-wrap-bg">
                <div class="over-wrap">
                    <?php
                        $posts = get_field('crew');
                        if ( $posts ) :?>
                        <ul class="crew-wrap">
                            <?php foreach( $posts as $p): ?>
                                <?php
                                $img_crew = wp_get_attachment_image_src( get_post_thumbnail_id( $p->ID ), 'thumbnail' );
                                ?>
                                <li><img src="<?php echo $img_crew[0]; ?>" alt="crew"></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                    <div class="meta-wrap">
                    <?php
                    if ( get_the_terms( $the_query->ID, 'portfolio_tag' ) ) {
                        echo '
                        <div class="tag-wrap"><i class="demo-icon icon-tag"></i> ' . strip_tags(get_the_term_list($the_query->ID, 'portfolio_tag', '', ' , ')) . '</div>';
                    }
                    if ( $location = get_field('location') ) {
                        echo '<div class="location-wrap"><i class="demo-icon icon-location-circled"></i> '.$location.'</div>';
                    }

                    ?>
                        <a class="show-popup" href="<?php echo $fullImg[0]; ?>">Detail Image</a>
                    </div>
                </div><!-- .over-wrap -->
            </div><!-- .over-wrap-bg -->
        </figure>
        <div class="desc-wrap">
            <?php
            the_title('<h4 class="title">', '</h4>');
            
            if ( $getTheContent = get_the_content() ) :
                echo '
                <hr>
                <div class="content-wrap">
                '.$getTheContent.'
                </div>';
            endif;
            ?>
        </div>
    </div>
</div><!-- .grid-item -->

붙혀 넣기 한 후 2line에 global $the_query; 를 추가 하고 코드를 정리해서 저장합니다.

다시 index.php 파일로 돌아와서

index.php
		<!-- portfolio -->
		<section id="section_3" class="portfolio">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <h4 class="under-bar text-center mb-5" >ABOUT US</h4>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 px-0">
                        <div class="grid ajax-portfolio">
                            <div class="grid-sizer"></div>
                            <?php
                            $paged = 1;
                            $args = array(
                                'post_type'         => 'portfolio',
                                'orderby'           => 'date',
                                'order'             => 'DESC',
                                'posts_per_page'    => 6,
                                'post_status'       => 'publish',
                                'paged'             => $paged,
                            );
                            $the_query = new WP_Query( $args );
                            if ( $the_query->have_posts() ) :
                                while( $the_query->have_posts() ) : $the_query->the_post();
                                    get_template_part( 'template-parts/content', 'portfolio' );
                                endwhile; wp_reset_postdata();
                            endif;
                            ?>
                        </div><!-- .grid .ajax-portfolio -->
                    </div><!-- .col-12 -->
                </div><!-- .row -->
                <div class="row">
                    <div class="col-12 text-center mt-5">
                        <button id="btn-load-more" class="zeein-button zeein-button-dark" data-security="<?php echo wp_create_nonce('load_more_portfolio'); ?>">VIEW MORE PORTFOLIO</button>
                    </div><!-- .col-12 -->
                </div><!-- .row -->
            </div><!-- .container -->
        </section>

잘라낸 부분을 정리하면 위와 같은 소스가 남게 됩니다.

여기까지 저장 하고 화면을 새로고침 해 보면 예정과 동일한 화면이 노출 되는 것을 확인 하실 수 있습니다.

get_template_part() 함수의 사용방법을 잘 익혀두면 반복적으로 사용하는 부분을 템플릿화 해서 편리하게 관리할 수 있습니다.
<?php get_template_part( 'template-parts/loop', 'index' ); ?>
예를 들어 위와 같은 경우 테마폴더의 template-parts 폴더에 loop-index.php 파일이 있는지 확인 후 불러 옵니다. 만약 파일이 없는경우 loop.php 이 있는지도 검사해서 있는경우 loop.php 파일을 불러 옵니다.
loop-index.php(없다면) > loop.php
Share this

Leave your question or feedback

따뜻한 말한마디가 블로거를 춤추게 합니다. 이메일 주소는 공개되지 않습니다.