WebProgram/Tistory

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

Total Fix! 2018. 5. 30. 14:59

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


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

이 방법은 문단과 문단 사이를 <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 my-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, my-4는 Bootstrap 4의 스타일 시트 클래스로 각각 "width: 100%;", "margin-top: 1.5rem;margin-bottom: 1.5rem"을 가리킵니다.


Bootstrap 4를 쓰지 않는다면 w-100과 my-4를 지우고 style="width: 100%;margin-top: 1.5rem;margin-bottom: 1.5rem"을 클래스 뒤에 붙여 넣으시면 됩니다.

광고 위아래 여백을 주는 것은 문단 사이의 <br> 태그를 대체하기 때문에 광고 위아래 간격이 없어지기 때문입니다.


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

(이 부분 스크립트 변경)


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


$length = parseInt($pBr.length / 2); <p><br></p> 태그 개수를 세고 중간 값을 구한 후 정수로 바꿉니다.


if($length > 3 )는 만약 글이 너무 짧아 8줄 이하면 광고는 무시하게 됩니다.


$pBr.eq($length).replaceWith($AdCode); 는 $length번째 <p><br></p>를 찾아 <br> 태그 대신 광고를 삽입합니다.


$(".google-ad-articleCenter-area").remove(); 원래 위치 광고는 지웁니다.


<div class="articleArea">
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
	<p>
		<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>
	</p>
	<p>본문 문단</p>
	<p><br></p>
	<p>본문 문단</p>
</div>


8번의 문단 띄기를 <p><br></p>로 구성되어 있어야 합니다.

항상 정 중앙에 광고를 띄웁니다.