본문 바로가기

티스토리 인피드 광고 넣는 법

반응형 인피드 광고


 
 
현재 블로그 스킨은 모바일과 데스크탑에서 글 목록의 레이아웃이 다르기 때문에 모바일과 데스크탑 구분하여 인피드 광고를 넣도록 코드를 짰다.
 
먼저 아래의 코드가 이 블로그의 현재 글 목록 html 코드다.
(치환자가 그냥 작동해버리길래 방지를 위해서 ## 앞에 숫자 1을 넣었다)

<s_article_rep>
  <s_index_article_rep>
    <div class="post-item">
      <a href="[1##_article_rep_link_##]">
        <div class="article-info">
          <span class="thum">
            <s_article_rep_thumbnail>
              <s_not_var_big-thumbnail>
                <img src="//img1.daumcdn.net/thumb/C300x200/?fname=[1##_article_rep_thumbnail_raw_url_##]" alt="">
              </s_not_var_big-thumbnail>
              <s_if_var_big-thumbnail>
                <img src="//img1.daumcdn.net/thumb/C960x640/?fname=[1##_article_rep_thumbnail_raw_url_##]" alt="">
              </s_if_var_big-thumbnail>
            </s_article_rep_thumbnail>
          </span>
        </div>
        <div class="article-info">
          <span class="category">[1##_article_rep_category_##]</span>
          <s_if_var_view-thumbnail-date>
            <span class="date">
              <s_if_var_short-date>[1##_article_rep_simple_date_##]</s_if_var_short-date>
              <s_not_var_short-date>[1##_article_rep_date_##]</s_not_var_short-date>										
            </span>
          </s_if_var_view-thumbnail-date>
          <span class="title">[1##_article_rep_title_##]</span>
          <s_if_var_view-thumbnail-excerpt>
            <span class="excerpt">[1##_article_rep_summary_##]</span>
          </s_if_var_view-thumbnail-excerpt>
        </div>
      </a>
    </div>																	
  </s_index_article_rep>
</s_article_rep>

 
이 코드 바로 다음 위치에 아래의 애드센스 인피드 광고 코드가 들어간다
 
현재 블로그 스킨은 모바일과 데스크탑에서 글 목록의 레이아웃이 다르기 때문에 모바일과 데스크탑 구분하여 인피드 광고를 넣도록 코드를 짰다.
 

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 스크립트가 여러 번 실행되지 않도록 전역 플래그로 체크
    if (window.infeedAdsInitialized) return;
    window.infeedAdsInitialized = true;
    var chInfeed = 0;
    var chInfeedAdSenseShow = 0; // 0 = 인피드 광고 적용, 1 = 비적용
    var chInfeedAdSenseInsert = 4; // 몇 개마다 광고 추가할지 설정

    if (chInfeedAdSenseShow === 0) { 
        // 모든 포스트 요소를 가져옴
        const postItems = document.querySelectorAll('.post-item'); // 스킨에 맞추어 편집

        postItems.forEach(function(postItem, index) {
            // index는 0부터 시작하므로 1을 더해 실제 순번으로 계산
            var chInfeed = index + 1;
            if (chInfeed % chInfeedAdSenseInsert === 0) {
                // 이미 다음 요소에 광고 컨테이너가 있다면 건너뜁니다.
                if (postItem.nextElementSibling && postItem.nextElementSibling.id === 'ads-container') {
                    return;
                }

                const isMobile = window.innerWidth < 768; // 768px 미만은 모바일

                // 광고를 삽입할 div 생성
                const adContainer = document.createElement('div');
                adContainer.id = 'ads-container';
                adContainer.style.width = '100%'; // 화면 크기에 맞춰 폭 100%로 설정
                adContainer.style.margin = '10px auto'; // 위아래 여백, 가운데 정렬
                adContainer.style.padding = '0'; // 불필요한 패딩 제거
                
                const adIns = document.createElement('ins');
                adIns.className = 'adsbygoogle';
                adIns.setAttribute('data-ad-format', 'fluid');
					adIns.setAttribute('style', 'display: block !important;');
                adIns.setAttribute('data-ad-layout-key', isMobile ? '모바일용 레이아웃키' : '데스크탑용 레이아웃키');
                adIns.setAttribute('data-ad-client', 'ca-pub-애드센스 클라이언트');
                adIns.setAttribute('data-ad-slot', isMobile ? '모바일용 slot 숫자' : '데스크탑용 슬롯 숫자'); 
                adContainer.appendChild(adIns);

                // 광고 로드 (adsbygoogle 객체가 있거나 새로 생성)
                (adsbygoogle = window.adsbygoogle || []).push({});

					// 광고 로드가 완료되면 높이를 자동으로 조정
                adIns.onload = function() {
                    adContainer.style.height = 'auto'; // 광고가 로드되면 높이를 자동으로 설정
                };

                // 해당 포스트 바로 뒤에 광고 컨테이너 삽입
                postItem.insertAdjacentElement('afterend', adContainer);
            }
        });
    }
});
</script>

 
 
이렇게 해서 이 블로그는 인피드 광고를 문제 없이 표시하게 되었다.


loading