Archived topic
Use Adsense In-article ad within pages content
5 replies · Started by George on February 14, 2023
I am trying to find an implementation that will allow posting an Adsense in-article ad every 12 paragraphs within the main content area of my Pages.
I found one guide that suggests using this code in the functions.php
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = ' Paste your AdSense Code Inside this quote';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 12, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
1. Will this also work if I just use this code as a Hook for all pages and enable the "Execute PHP" checkbox?
2. Any other ways to automate publishing ads within the content?
Hi there,
1. No, the GP Hooks are only for outputting code in the front end. That code is a filter hook and it needs to be executed before that. So it must go in a child themes functions.php or be added using a plugin like code snippets.
2. i would recommend using the Ad Sense plugin, its so much better at filtering the content to insert those codes, and it will handle ever X paragraphs whereas that code will only insert after the 12th paragraph.
Thanks David. Which adsense plugin do you recommend? And is there a way to use it without lowering pagespeed metric?
Well that was dumb of me lol - i meant the Ad Inserter plugin ie. this one:
https://wordpress.org/plugins/ad-inserter/
The main issue with ads affecting performance is the advert scripts themselves.
many optimization plugins like permitters or Flying scripts will allow you defer loading those scripts so they don't block the initial page load.
Thanks David!
You're welcome