如何拆分<data:post.body/>为两半以在文章中插入谷歌广告?
Hey there! As someone who’s both a blogger and dev, I totally get the need to split your post content and slot in Google Ads for monetization—let’s walk through exactly how to do this, assuming you’re working with Blogger (since you mentioned the <data:post.body/> tag, which is specific to Blogger templates).
<data:post.body/> Tag in Your Template First, head to your Blogger dashboard → Theme → Edit HTML. Use the search function (Ctrl/Cmd + F) to find the <data:post.body/> line. This is where your post content gets rendered.
Instead of just rendering the raw post body, we’ll wrap it in a container and add a small JavaScript snippet to split the content and inject the ad. Here’s the code to replace the original <data:post.body/>:
<div id="post-content-wrapper"> <data:post.body/> </div> <script> // Wait for the page to fully load content document.addEventListener('DOMContentLoaded', function() { const contentWrapper = document.getElementById('post-content-wrapper'); const paragraphs = contentWrapper.querySelectorAll('p'); // Only run if there are enough paragraphs to split (adjust this number as needed) if (paragraphs.length >= 4) { // Calculate the middle point (you can tweak this—e.g., use 2 to insert after 2nd paragraph) const splitIndex = Math.floor(paragraphs.length / 2); // Create a container for your Google Ad const adContainer = document.createElement('div'); adContainer.style.margin = '2rem 0'; // Add spacing around the ad adContainer.className = 'middle-post-ad'; // Paste your Google AdSense code here (replace with your actual ad details) adContainer.innerHTML = ` <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-YOUR_AD_CLIENT_ID" data-ad-slot="YOUR_AD_SLOT_ID" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> `; // Insert the ad right after the middle paragraph paragraphs[splitIndex].after(adContainer); } }); </script>
- Adjust the split point: If you don’t want the exact middle, replace
Math.floor(paragraphs.length / 2)with a fixed number (like2to insert after the 2nd paragraph). - Style the ad container: Add CSS to your template’s
<style>section to control spacing, alignment, etc.—for example:.middle-post-ad { text-align: center; margin: 30px 0; padding: 10px; border-top: 1px solid #eee; border-bottom: 1px solid #eee; } - Validate ad code: Make sure you’re using the correct AdSense code from your account—don’t forget to replace
YOUR_AD_CLIENT_IDandYOUR_AD_SLOT_IDwith your actual values.
Save your template, then view a published post with enough paragraphs. The ad should appear right where you specified! If it doesn’t show up, double-check that your AdSense account is approved, the code is correct, and the post has enough paragraphs to trigger the split.
内容的提问来源于stack exchange,提问作者Peter Perez

