Code chèn quảng cáo AdSense thủ công trong nội dung bài viết

ARTRU

Mặc dù AdSense có hỗ trợ chèn quảng cáo trong nội dung bài viết, nhưng nó hoạt động không được hoàn hảo cho lắm. Rất hay bị vỡ layout website do bị chèn quảng cáo lung tung.

Hiện tại mình đang sử dụng mã PHP này trong Oxygen Builder để load quảng cáo AdSense sau mỗi 7 dòng, cụ thể là 7 thẻ <p>.

Bước 1: Tắt quảng cáo tự động.

Tắt quảng cáo tự động AdSense
Tắt quảng cáo tự động AdSense

Bước 2: Tạo quảng cáo unit In-article Ad.

Tạo quảng cáo In-article AdSense
Tạo quảng cáo In-article AdSense

Bước 3: Thêm mã javascript vào phần footer.

Ở dòng thứ 4: var paragraphs = document.querySelectorAll('.wp-content p'); bạn hãy thay đổi .wp-content bằng class của phần tử nội dung bài viết. Mỗi theme mỗi khác nên bạn cần kiểm tra bằng công cụ Devtool (F12).

Nhớ đổi "xxxxxx" thành mã riêng của bạn dựa vào đoạn script mà bạn vừa tạo ở bước 2.

<script>
document.addEventListener("DOMContentLoaded", () => {
    var count = 0;
    var paragraphs = document.querySelectorAll('.wp-content p');
    for (var i = 0; i < paragraphs.length; i++) {
        count++;
    if (count % 7 === 0) {
            var ad_in_content = document.createElement('ins');
    ad_in_content.setAttribute('class', 'adsbygoogle');
    ad_in_content.setAttribute('style', 'display:block; text-align:center;');
    ad_in_content.setAttribute('data-ad-layout', 'in-article');
    ad_in_content.setAttribute('data-ad-format', 'fluid');
    ad_in_content.setAttribute('data-ad-client', 'ca-pub-xxxxxx');
    ad_in_content.setAttribute('data-ad-slot', 'xxxxxx');
    paragraphs[i].insertAdjacentElement('afterend', ad_in_content);
        }
    }

    const ad_script = document.createElement("script");
    ad_script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxx";
    ad_script.setAttribute("crossOrigin", "anonymous");
    document.body.appendChild(ad_script);
    ad_script.addEventListener("load", function () {
        document.querySelectorAll(".adsbygoogle").forEach(function (ad_script) {
            (window.adsbygoogle = window.adsbygoogle || []).push({});
        });
    });
});
</script>
BÌNH LUẬN

Bài Viết Liên Quan