Show Post Tags Like Hashtags on Divi Blog Feed

작업하다가 Divi Theme 블로그 모듈 피드 화면에 태그를 보여줘야해서 정리.

1. Divi Theme Option > Integration > Add code to the < head > of your blog

<script>
document.addEventListener('DOMContentLoaded', function () {
  const posts = document.querySelectorAll('.et_pb_blog_grid .et_pb_post');

  posts.forEach(post => {
    const readMore = post.querySelector('.more-link');
    const postId = post.id.replace('post-', '');

    // AJAX로 각 포스트 태그를 불러오기
    fetch(`/wp-json/wp/v2/posts/${postId}`)
      .then(response => response.json())
      .then(data => {
        if (data.tags && data.tags.length) {
          // 태그 정보를 가져옴
          const tagIds = data.tags;

          // 각 태그 ID에 대해 다시 요청
          Promise.all(
            tagIds.map(tagId => fetch(`/wp-json/wp/v2/tags/${tagId}`).then(res => res.json()))
          ).then(tagDataList => {
            const tagContainer = document.createElement('div');
            tagContainer.className = 'custom-tags';

            tagDataList.forEach(tag => {
              const tagLink = `<a class="tag-item" href="${tag.link}">#${tag.name}</a>`;
              tagContainer.innerHTML += tagLink + ' ';
            });

            if (readMore) {
              readMore.insertAdjacentElement('beforebegin', tagContainer);
            }
          });
        }
      });
  });
});
</script>

2. Divi Theme Option > General > Custom CSS

.custom-tags {
    margin-top: 10px;
    margin-bottom: 10px;
}
.custom-tags .tag-item {
    display: inline-block;
    margin-right: 6px;
    padding: 4px 10px;
    background: #f0f0f0;
    border-radius: 16px;
    font-size: 12px;
    color: #333;
}

코멘트

댓글 남기기