Code to manually insert AdSense ads in article content
Although AdSense supports inserting ads in article content, it doesn't work very well. Website layouts are often broken due to random ads being inserted.
Currently I am using this PHP code in Oxygen Builder to load AdSense ads every 7 lines, specifically 7 tags. <p>
.
Step 1: Turn off automatic ads.

Step 2: Create In-article Ad unit ads.

Step 3: Add javascript code to the footer section.
In the 4th line: var paragraphs = document.querySelectorAll('.wp-content p');
please change .wp-content
equal to the class of the article content element. Each theme is different so you need to check with Devtool (F12).
Remember to change "xxxxxx
" into your own code based on the script you just created in step 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>
Related Articles