본문 하단의 관련 글은 포스트 간의 밀도를 높여 검색엔진최적화(SEO)에 좋고 사용자 체류 시간도 늘어날 확률이 높아진다. 이 글에서는 플러그인 없이 본문 하단에 태그 관련 글을 넣는 방법을 설명한다.
워드프레스에서 관련글을 넣는 방법은 ‘Contextual Related Posts’ 플러그인이나 JetPack 같은 SEO플러그인의 관련 글 기능을 활성화시키면 된다. 대신 플러그인을 쓰면 사이트가 무거워지고 자기가 원하는 맞춤형은 포기해야 한다.
태그 사용법과 관련글 넣는 방법
관련 글은 대개 카테고리 내의 다른 글을 노출시키는 방식이다. 나는 카테고리 대신 태그 관련글을 넣기로 했다. 태그가 카테고리보다 본문과 더 깊은 관련성을 가지기 때문이다.
다만, 태그 관련글을 노출하려면 그 태그에 관련된 글이 적어도 두 개 이상은 있어야 한다. 태그를 남발하는 경우가 많은데, 사실 태그는 작은 카테고리 용도라고 생각하면 된다. 태그 관련 글이 5개 정도 생기면 새로운 태그를 생성하는 식으로 운영하면 된다.
태그 관련글 표출 순서
functions.php 코드
아래 코드는 현재 이 사이트에 노출되고 있는 “functions.php” 코드이다. 분문 하단에 지정된 태그 중에서 관련 글이 가장 작은 태그를 뽑고 그 태그와 관련 된 글 중에서 게시일자와 가장 가까운 순으로 3개를 노출하라는 명령이다.
그리고 태그 관련글 리스트 아래에는 태그 목록도 마찬가지 방식으로 관련글이 적은 태그 순으로 6개까지만 노출하라는 코드이다.
이러한 방식을 택한 이유는 태그가 분류 방식이므로 관련 글이 많은 태그는 대분류에 해당하고 관련 글이 가장 적은 태그가 가장 소분류에 해당하는 태그이기 때문이다.
예를들면, 관련 글이 맛집(10개) > 강남구 맛집(20개) > 서울 맛집(30개) 순서로 있다면 이 순서로 태그 관련글을 뽑고 목록도 작은 분류에서 큰 분류 순으로 배치된다.
사용자는 좁은 범위의 구체적인 정보를 먼저 얻고, 검색엔진도 문서 간의 긴밀한 연관성을 파악하기 쉽다. 직관에 반하긴 하나 롱테일(Long-tail) 우선 원칙이 관련글에도 적용된다.
/* ===== 8. 태그(적은순) 기반 문맥 관련 글 + 태그 목록 출력 (최종 확정형) ===== */
add_filter('the_content', function($content) {
if (!is_singular('post') || is_admin() || is_feed()) return $content;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
// 1. 태그 정렬: 사용 빈도가 낮은(구체적인) 태그 우선
usort($tags, function($a, $b) {
return $a->count - $b->count;
});
$main_tag = $tags[0];
$main_tag_id = $main_tag->term_id;
$main_tag_name = $main_tag->name;
// --- [섹션 A] 관련 글 추출 (작성일 기준 근접순) ---
global $wpdb;
$current_post_date = $post->post_date;
$orderby_closest_date = function($orderby) use ($current_post_date, $wpdb) {
return " ABS( TIMESTAMPDIFF(SECOND, '$current_post_date', {$wpdb->posts}.post_date) ) ASC ";
};
add_filter('posts_orderby', $orderby_closest_date);
$related_args = array(
'tag__in' => array($main_tag_id),
'post__not_in' => array($post->ID),
'posts_per_page' => 3,
'ignore_sticky_posts' => 1,
);
$related_query = new WP_Query($related_args);
remove_filter('posts_orderby', $orderby_closest_date);
$related_html = '';
if ($related_query->have_posts()) {
$related_html = '<section class="contextual-related-section">';
$related_html .= '<h3 class="related-title">' . esc_html($main_tag_name) . ' 관련 글 더보기</h3>';
$related_html .= '<ul class="related-list">';
while ($related_query->have_posts()) {
$related_query->the_post();
$related_html .= sprintf(
'<li><a href="%1$s" title="%2$s 바로가기">%2$s</a></li>',
get_permalink(),
get_the_title()
);
}
$related_html .= '</ul></section>';
wp_reset_postdata();
}
// --- [섹션 B] 태그 목록 출력 ---
$tag_html = '<div class="post-tags-ordered" aria-label="Post Tags">';
$display_tags = array_slice($tags, 0, 6);
foreach ($display_tags as $tag) {
$tag_link = get_tag_link($tag->term_id);
$tag_html .= sprintf(
'<a href="%s" class="ordered-tag-item" rel="tag">%s »</a>',
esc_url($tag_link),
esc_html($tag->name)
);
}
$categories = get_the_category($post->ID);
if (!empty($categories)) {
$cat = $categories[0];
$cat_link = get_category_link($cat->term_id);
$tag_html .= sprintf(
'<a href="%s" class="ordered-tag-item category-item">%s</a>',
esc_url($cat_link),
esc_html($cat->name)
);
}
$tag_html .= '</div>';
// 본문 하단에 관련 글 섹션과 태그 목록 결합
$content .= $related_html . $tag_html;
}
return $content;
}, 10);
CSS 추가하기
아래 코드는 “추가 CSS”에 넣은 양식 코드이다. 이 코드가 지시하는 대로 현재 이 문서 하단에 “SEO 관련글 더보기” 리스트와 그 아래에 태그 목록이 노출되고 있다.
.related-posts-section {
padding-top: 14px;
}
.related-list {
line-height: 1.3;
padding-left: 20px;
}
.related-list li {
padding: 6px 0;
}
.related-list li a {
text-decoration: none;
color: #0066ff;
}
.post-tags-ordered {
padding-top: 20px;
border-top: 1px solid #ddd;
font-size: 0.95rem;
}
.ordered-tag-item {
display: inline-block;
margin-right: 15px;
color: #0066ff;
text-decoration: none;
font-weight: 500;
transition: all 0.2s ease;
}
관련 글 리스트에 박스를 넣거나 폰트 색상을 예쁘게 하는 등 디자인을 넣고 싶다면 위 코드를 응용하면 된다.
본문 링크 제외한 관련글 넣기
본문에 수동으로 넣어둔 링크가 있다면 태그 관련글과 중복으로 노출될 위험이 있다. 글쓰기 문법과 마찬가지로 링크도 중복되면 감점이다.
다만, 이렇게 하면 본문 링크와 관련글과의 중복성을 체크하기 위한 서버에 아주 약간의 부담이 생길 수 있다. 플러그인에 비하면 아무것도 아니긴 하다.
본문 링크를 제외하고 관련 글을 넣으려면, 아래 코드를 위 코드의 // — [섹션 A] 관련 글 추출 (날짜 근접순) — 부분에 대체해서 넣어주면 된다.
// 2. 본문에서 이미 수동으로 링크한 포스트 ID 추출 (중복 노출 방지)
$exclude_ids = array($post->ID); // 현재 포스트 제외
preg_match_all('/href=["\']([^"\']+)["\']/', $content, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $url) {
$linked_post_id = url_to_postid($url);
if ($linked_post_id && !in_array($linked_post_id, $exclude_ids)) {
$exclude_ids[] = $linked_post_id;
}
}
}
// --- [섹션 A] 관련 글 추출 (날짜 근접순 정렬) ---
$current_post_date = $post->post_date;
$orderby_closest_date = function($orderby) use ($current_post_date, $wpdb) {
return " ABS( TIMESTAMPDIFF(SECOND, '$current_post_date', {$wpdb->posts}.post_date) ) ASC ";
};
add_filter('posts_orderby', $orderby_closest_date);
$related_args = array(
'tag__in' => array($main_tag_id),
'post__not_in' => $exclude_ids, // 본문 링크 글들 제외
'posts_per_page' => 3,
'ignore_sticky_posts' => 1,
);
$related_query = new WP_Query($related_args);
remove_filter('posts_orderby', $orderby_closest_date);
$related_html = '';
if ($related_query->have_posts()) {
$related_html = '<section class="related-posts-section">';
$related_html .= '<h3 class="related-title">' . esc_html($main_tag_name) . ' 관련 글 더보기</h3>';
$related_html .= '<ul class="related-list">';
while ($related_query->have_posts()) {
$related_query->the_post();
$related_html .= sprintf(
'<li><a href="%1$s" title="%2$s 바로가기">%2$s</a></li>',
get_permalink(),
get_the_title()
);
}
$related_html .= '</ul></section>';
wp_reset_postdata();
}
초경량화를 위해 이 워드프레스에는 플러그인을 거의 쓰지 않는다. 리디렉션 플러그인 Redirection과 이메일 WP Mail SMTP, 그리고 캐시 플러그인 WP-Optimize, 이렇게 딱 세 개다.
그 외 이 블로그에 적용된 대부분의 기능은 코드로 구현했다.
댓글