How to add AdSense to WordPress without a plugin (classic and block themes)
Key takeaways
- The wp_head action fires inside the head element, so a small function hooked to it outputs the AdSense code on every front-end page.
- Block themes also fire wp_head: WordPress renders block templates through template-canvas.php, which calls wp_head() inside the head.
- The the_content filter can insert an ad unit after a chosen paragraph; WordPress recommends checking in_the_loop() and is_main_query() when filtering content.
- In a block theme, a Custom HTML block placed in a template part such as the header or a single template can hold manual ad unit code.
- ads.txt must be reachable at the root of the domain, so upload it to the folder that serves your homepage.

To add AdSense to WordPress without a plugin, hook a function to wp_head that prints the AdSense code, add manual units with the the_content filter or a Custom HTML block in a template part, and upload ads.txt to your web root. This works with classic and block themes, survives theme updates when you use a child theme, and keeps the ad code exactly as Google provides it.
Why skip the plugin?
Plugins are convenient, but each one adds settings pages, scripts and update risk. For AdSense, the job is small: one tag in the head, optionally a few ad units, and one text file. Doing it in code also means you control exactly what is printed, which matters because Google’s code modification policy limits how the ad code can be changed.
Placeholders below: publisher ID ca-pub-0000000000000000, slot 1234567890.
Where do I put the code so it survives updates?
- Child theme
functions.php: the usual choice. Edits to a parent theme are overwritten on update. - A must-use plugin you write (
wp-content/mu-plugins/adsense.php): theme-independent, loads automatically, still “no third-party plugin”. - Not the parent theme’s
header.php, and not a block in the post editor for the head snippet.
Step 1: add the AdSense code with wp_head
The wp_head hook “prints scripts or data in the head tag on the front end” and is triggered by wp_head() inside <head>. Google asks for the AdSense code between <head> and </head> on every page (Where to place AdSense code in your HTML).
<?php
// functions.php (child theme) or wp-content/mu-plugins/adsense.php
add_action( 'wp_head', function () {
if ( current_user_can( 'edit_posts' ) ) {
return; // no ads for editors and admins while they work
}
?>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
crossorigin="anonymous"></script>
<?php
} );
Why print the tag instead of using wp_enqueue_script()? Enqueueing is the WordPress way for your own scripts and supports 'strategy' => 'async' since WordPress 6.3, but it appends a ver query string by default and needs an extra filter to add crossorigin. Printing the exact snippet avoids altering the URL Google gave you.
Does wp_head work with block themes?
Yes. Block themes have no header.php, but WordPress renders them through template-canvas.php, whose source contains <?php wp_head(); ?> inside <head> (template-canvas.php in WordPress core). The hook above therefore works the same on Twenty Twenty-Five and other block themes.
At this point, Auto ads work: turn them on for the site in AdSense. The rest of this guide covers manual units.
Step 2: insert an ad unit after a paragraph
The the_content filter runs on post content before it is printed. WordPress’s documentation recommends checking is_main_query() and in_the_loop() so you only touch the main content, not widgets or excerpts.
<?php
add_filter( 'the_content', function ( $content ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
if ( current_user_can( 'edit_posts' ) ) {
return $content;
}
if ( get_post_meta( get_the_ID(), 'no_ads', true ) ) {
return $content; // per-post opt-out
}
$ad = '<div class="ad-slot ad-slot--in-content">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="1234567890"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
$after = 2; // insert after the 2nd paragraph
$paragraphs = explode( '</p>', $content );
if ( count( $paragraphs ) <= $after + 1 ) {
return $content; // too short: skip the ad
}
$last = count( $paragraphs ) - 1;
foreach ( $paragraphs as $i => $p ) {
if ( $i < $last ) {
$paragraphs[ $i ] .= '</p>'; // restore the tag removed by explode()
}
if ( $i + 1 === $after ) {
$paragraphs[ $i ] .= $ad;
}
}
return implode( '', $paragraphs );
} );
Notes:
- The short-post check avoids putting an ad at the very end of thin content.
explode()removes every</p>, so the loop adds it back to each piece except the last one, which holds whatever follows the final paragraph.- The
no_adscustom field gives editors a per-post switch: add a custom field namedno_adswith any non-empty value to a post (for example a sensitive news story or a sponsored article with its own rules) and the filter leaves it untouched.get_post_meta()withtrueas the third argument returns a single value, an empty string when the field does not exist. - Splitting on
</p>is simple and predictable. If your posts use many nested blocks, therender_blockapproach below is more precise. - Reserve height for the slot with CSS (
.ad-slot { min-height: 280px; }in your child theme stylesheet) to limit layout shift. See preventing CLS from ads.
Step 3: ad units in block themes
Block themes give you two clean options.
Option A: a Custom HTML block in a template part
Template parts are reusable sections such as the header, footer or sidebar, stored in the theme’s /parts folder and included with the Template Part block (Template Parts handbook). In the Site Editor:
- Open Appearance, then Editor, then the template or template part you want (for example “Single Posts” or “Sidebar”).
- Add a Custom HTML block where the ad should appear.
- Paste the ad unit code exactly as generated by AdSense.
- Save the template or template part.
Option B: the render_block filter
render_block filters the HTML of each block and receives the block’s name. You can append an ad after a specific block, for example after the first image in a post:
<?php
add_filter( 'render_block', function ( $block_content, $block ) {
static $done = false;
if ( $done || ! is_singular( 'post' ) || is_admin() ) {
return $block_content;
}
if ( 'core/image' !== $block['blockName'] ) {
return $block_content;
}
$done = true;
return $block_content . '<div class="ad-slot"><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-0000000000000000" data-ad-slot="1234567890" data-ad-format="auto" data-full-width-responsive="true"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>';
}, 10, 2 );
The static $done flag limits it to one insertion per request.
Step 4: upload ads.txt
ads.txt has to be served at https://your-domain/ads.txt. On most installs that means the folder containing wp-config.php and index.php. Upload a plain text file:
google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0
If WordPress is installed in a subfolder, or an SEO plugin serves a virtual ads.txt, read ads.txt on WordPress without a plugin for the conflicts to watch.
Step 5: verify
- Log out (or use a private window), because the code above skips logged-in editors.
- View the page source and search for
adsbygoogle.js. It should appear once, inside<head>. - Check one post for the
<ins class="adsbygoogle"element after the second paragraph. - Clear any page cache (plugin, host or CDN) if the new HTML does not appear.
- Open
/ads.txtand confirm plain text.
Do not click your own ads to check that they work. The own-clicks and testing guide lists safe ways to test.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Script missing from page source | Code in the wrong file, page cache, or you are logged in | Check the file is loaded, purge cache, log out |
| Script present twice | A theme option or old plugin also adds AdSense | Remove one; keep a single head snippet |
| Ad unit printed in widgets or excerpts | the_content filter without loop checks |
Keep in_the_loop() and is_main_query() |
| Ads blank, console shows “No slot size for availableWidth=0” | Ad container has no width (floated, hidden, collapsed) | Give the container a width; avoid hidden parents |
| Ads load very late | A performance plugin delays or combines third-party JavaScript | Exclude adsbygoogle.js and the inline push scripts from delay and combine features |
What about Auto ads and manual units together?
Both approaches above coexist with Auto ads. Google states that Auto ads detect existing ads on the page; the Auto ads vs manual ad units guide explains how to keep control with ad load limits and exclusions. For unit types that suit posts and archives, see in-article, in-feed and Multiplex units.
Frequently asked questions
Where should I put the code: functions.php or header.php?
Use a function hooked to wp_head in a child theme's functions.php (or a small must-use plugin you own). Editing header.php works only for classic themes and is lost when the theme updates. Block themes have no header.php, but WordPress still fires wp_head, so the hook works with both theme types.
Does this work with block themes like Twenty Twenty-Five?
Yes. Block themes are rendered through WordPress's template-canvas.php, which calls wp_head() inside the head element. A function hooked to wp_head therefore prints the AdSense code just as it would with a classic theme. For manual units, use a Custom HTML block in a template part or the render_block filter.
Why are my ads not showing after adding the code?
Check the page source for the AdSense script: if it is missing, the hook did not run or a cache is serving old HTML. If it is present, check that the site is approved, Auto ads or the unit is active, and that a performance plugin is not delaying or combining the adsbygoogle script. Google says new Auto ads settings can take up to an hour to appear.
Should I hide ads from logged-in administrators?
It is optional but sensible. Wrapping the output in a check such as current_user_can('edit_posts') stops ads loading while you edit and preview, which keeps your own impressions out of reports and removes the temptation to click. Do not click your own ads to test them.
Sources
- wp_head · WordPress Developer Resources
- the_content · WordPress Developer Resources
- Template Parts · WordPress Theme Handbook
- render_block · WordPress Developer Resources
- Where to place AdSense code in your HTML · Google AdSense Help
Related guides
- How to add ads.txt to WordPress without a plugin (and avoid conflicts with virtual ads.txt files)
Add ads.txt to WordPress by uploading one file to the web root: where that is, why it beats plugin-generated virtual files, and how to fix plugin conflicts.
- Auto ads vs manual ad units: which one to use, and how to combine them
Auto ads or manual ad units? Compare control, formats, page and area exclusions, and how AdSense combines both on one page without double work.
- In-article, In-feed and Multiplex ads: where each native AdSense format belongs and how to place the code
Where AdSense native formats go and how to code them: In-article ads between paragraphs, In-feed ads inside list loops, and Multiplex grids after articles.
- Clicking your own AdSense ads: why it is prohibited and how to test ads safely
Clicking your own AdSense ads is prohibited for any reason. How to check ads and layouts without clicking, what to tell staff and family, what to do after a slip.
- How to prevent layout shift (CLS) from AdSense ads by reserving slot space
Stop AdSense ads from shifting your layout: reserve slot space with min-height or fixed CSS sizes, handle unfilled slots, and keep Auto ads shifts in check.