WebProgram/Tistory

[애드센스] 광고 본문 중간에 자동으로 삽입하기 (서식 지정 없음)

Total Fix! 2018. 5. 20. 02:05

애드센스 광고를 본문 중간에 삽입하려는 방법입니다.



이 방법은 기존의 방법처럼 특정 위치에 서식을 이용하는 방법이 아니라 문단과 문단 사이를 찾아 자동으로 삽입하는 것입니다.

이 방법은 문단과 문단 사이를 <br> 태그를 이용하는 경우 효과가 있습니다.


우선 본문의 구조를 확인해 봐야 합니다.

저의 경우 본문의 구조는 다음과 같이 구성되어 있습니다.


<div class="articleArea">
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
</div>


자신의 블로그 구조를 확인하였다면 삽입할 광고를 준비합니다.


<div class="google-ad-articleCenter-area w-100">
	<div class="google-ad-articleCenter w-100 mt-4">
		<ins class="adsbygoogle"
			style="display:block; text-align: center;"
			data-ad-client="ad-client"
			data-ad-slot="ad-slot"
			data-ad-format="auto">
		</ins>
		<script>
			(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
	</div>
</div>


위의 w-100, mt-4 는 Bootstrap 4의 스타일 시트 클래스로 각각 "width: 100%;", "margin-top: 1.5rem"을 가리킵니다.


이제 jQuery를 이용하여 준비된 광고를 적당한 위치에 삽입하겠습니다.


<script type="text/javascript">
	$pBr = $(".articleArea p > br");
	$AdCode = $(".google-ad-articleCenter-area").html();
	$pBr.eq(2).replaceWith($AdCode);
	$(".google-ad-articleCenter-area").remove();
</script>


위 내용은 간단히 말하면 <p><br></p> 태그의 개수를 찾고 중간 부분에 광고를 넣으러는 내용입니다.


$pBr.eq(2)는 <p><br></p> 태그중 2번째 <br> 태그를 찾는 것입니다.


따라서 위의 스크립트를 적용한 결과는 아래와 같게 됩니다.


<div class="articleArea">
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
	<p>
		<div class="google-ad-articleCenter-area w-100">
			<div class="google-ad-articleCenter w-100 mt-4">
				<ins class="adsbygoogle"
					style="display:block; text-align: center;"
					data-ad-client="ad-client"
					data-ad-slot="ad-slot"
					data-ad-format="auto">
				</ins>
				<script>
					(adsbygoogle = window.adsbygoogle || []).push({});
				</script>
			</div>
		</div>
	</p>
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
</div>


특별히 어려운 내용은 없습니다.

그러나 이 방법도 완벽한 방법이 아니므로 자신의 블로그에 맞는 방법을 생각해 보셔야 합니다.


감사합니다.