워드프레스 카테고리 관련글 보이게 하는방법

워드프레스 본문 아래에 같은 카테고리에 있는 관련 최근글을 보이게하는 방법입니다. 컨텐츠에서 유사한 게시물을 추천해서 다른게시물을 소개해 접속률을 높이고, 사이트 머무는 시간을 늘여주는데 도움이 됩니다.

카테고리 관련글 보이게 하는방법

Elements를 활성화

워드프레스 GeneratePress 테마를 기준으로 소개합니다. 관리자모드 > 외모 > GenerratePress 에 접속해서 아래 그림과같이 Modules에서 Elements를 활성화합니다.

카테고리 관련글 보이게 하는방법

New Element hook모드 추가

활성화한다음 관리자모드 > 외모 > Elements에서 ‘Add New Element’를 눌러서 ‘hook’타입으로 생성후 제목을 입력한다음 아래 소스를 입력합니다.

<!-- Related Posts Section -->
<div class="related-posts">

    <?php 
    $categories = get_the_category();
    
    // Check if the post has categories
    if (!empty($categories) && !is_wp_error($categories)):

        // Get the ID of the primary category (first category in the list)
        $primary_category_id = $categories[0]->term_id;

        // Display the primary category name
        ?>
        <h4>
            <?php echo esc_html($categories[0]->name); ?> 카테고리의 추천게시물
        </h4>

        <?php
        // Define the arguments for the related posts query
        $query_args = array(
            'cat'            => $primary_category_id,
            'post_type'      => 'post',
            'post__not_in'   => array(get_the_ID()),
            'posts_per_page' => '5',
            'orderby'        => 'rand'
        );

        $related_cats_post = new WP_Query($query_args);

        // Check if there are any related posts
        if ($related_cats_post->have_posts()): 
        ?>
            <!-- Display the list of related posts -->
            <ul>
                <?php while ($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
                    <li>
                        <a href="<?php the_permalink(); ?>">
                            <?php the_title(); ?>
                        </a>
                    </li>
                <?php endwhile; ?>
            </ul>

            <?php 
            // Restore the original post data
            wp_reset_postdata();
        endif; 
    endif;
    ?>

</div><!-- End of Related Posts Section -->

Execute PHP 활성화

입력후 Settings에서 hook을 generate_after_content를 선택해서 본문이후에 표시가 되게 하고, exec php를 활성화 해줍니다.

GP설정

DISPLAY 위치 확인

바로 옆의 탭 ‘Display Rules’에서 location을 ‘글’로 입력후 화면 우측 ‘공개’버튼 (아래 사진에서는 업데이트’ 버튼 위치)을 눌러 입력을 완료합니다.

EDIT HOOK

추가CSS 입력

관리자모드 > 외모 > 사용자정의 > 추가CSS 맨아래 다음을 추가합니다.

/* 관련 글 */
.related-posts {
    margin-top: 30px;
    border: 1px solid #ccc;
    padding: 10px 10px 3px 10px;
}

.related-posts ul * {
    font-size: 0.9rem;
}

.related-posts h4 {
    font-weight: 550;
    border-bottom: 1px solid #eee;
    padding-bottom: 5px;
    margin-bottom: 15px;
}

.related-posts ul {
    margin-bottom: 8px;
}

추가CSS설정

완료하면 아래와같이 게시글 밑에 추가되었습니다.

관련글 보이기

그외 ‘YARPP – Yet Another Related Posts Plugin’, ‘Contextual Related Posts’ 등 전용 플러그인도 있습니다.

기타 상세 조치는 아래 링크를 참고하면 됩니다.
https://www.thewordcracker.com/basic/워드프레스-관련-글-목록-표시하기/