I have been using Ad Inserter to place AdSense for a while because I think it is better than its competitors.
Having said that I enjoy having a few plugins, lightweight plugins, and plugins with only the options that I really need.
If you check Ad Inserter or AdInserter Pro carefully, you will probably discover that you might not need many of its functionalities.
When I came to that realization, I started looking for code snippets to replace the ad inserter plugin.
These are some of the best codes to insert all types of ads without using a problem.
This is how yo create a shortcode
// The shortcode function
function ad_shortcode_01() {
// Advertisement code
$string .= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-0123456789101112"
data-ad-slot="9876543210"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
// Ad code returned
return $string;
}
// Register shortcode
add_shortcode('my_ad_code', 'ad_shortcode_01');
You can create more code by renaming the function to something else easy to remember such as “ad_shortcode_02”
Table of Contents
- How to Insert the Code Snippet
- Searching for a Code Snippet?
- Code Snippet to Insert Adsense Ads (#1)
- Code Snippet to Insert Adsense Ads (#2)
- Code Snippet to Insert Adsense Ads (#3)
- Code Snippet to Insert Adsense Ads (#4)
- Code Snippets to Insert Adsense Ads #5
- Code Snippet to Insert Adsense Ads (#6)
- Keep this Mind
How to Insert the Code Snippet
Code snippets plugins have never been as popular as now, so finding one to do this job isn’t that difficult.
I have used Code Snippets on some sites or WPCode since those two are the dominant plugins in the WordPress repository.
Inserting the ad units code inside the code snippet might make changing and adapting things a bit more complicated, so shortcodes are the perfect companions if you place Adsense ads without a plugin.
Searching for a Code Snippet?
Anchor ads can be easily added with the help of the elements sections from GeneratePress or other plugins.
Sidebars Ads can be added using an HTML widget.
You can also use theme hooks to place anchor and sidebar ads.
I was looking for code snippets that can help me add AdSense ads after paragraphs, headings, unordered lists, and ordered lists.
Code Snippet to Insert Adsense Ads (#1)
There are many code snippets out there to insert ads, since I am not a coder, I can pick one and see if it does what I think it does.
I tried this code from CodexWorld and it works as expected.
/*
* Insert ads code into post content
* $adsCode: Specify code that wants to add
* $insertAfter: Specify paragraph number
*/
add_filter('the_content', 'cw_insert_post_ads');
function cw_insert_post_ads($content){
if(is_single()){
//ads code
$adsCode = '<div>Insert your ads code here</div>';
//insert after
$insertAfter = 2;
$closingP = '</p>';
$contentBlock = explode($closingP, $content);
foreach($contentBlock as $key => $con){
if(trim($con)) {
$contentBlock[$key] .= $closingP;
}
if(($key + 1) == $insertAfter){
$contentBlock[$key] .= $adsCode;
}
}
$content = implode('', $contentBlock);
}
return $content;
}
This works for one ad, however, you can use the code more than once if you make modifications to it.
This is an example of the code with modifications in it.
/*
* Insert ads code into post content
* $adsCode: Specify code that wants to add
* $insertAfter: Specify paragraph number
*/
add_filter('the_content', 'cw_insert_post_ads1');
function cw_insert_post_ads1($content){
if(is_single()){
//ads code
$adsCode = '<div>Insert your ads code here</div>';
//insert after
$insertAfter = 3;
$closingP = '</h2>';
$contentBlock = explode($closingP, $content);
foreach($contentBlock as $key => $con){
if(trim($con)) {
$contentBlock[$key] .= $closingP;
}
if(($key + 1) == $insertAfter){
$contentBlock[$key] .= $adsCode;
}
}
$content = implode('', $contentBlock);
}
return $content;
}
If you want to insert ads after heading, use </h2>, </h3> or </h4>instead of ‘</p> in line #15
The problem that I found with my implementation is that code is gonna insert the advertisement where you want to but if you don’t have headings or paragraphs, all advertisements will be inserted at the end of the post.
I noticed that problem because I checked a post with only two paragraphs or something.
Hopefully, you don’t have thin content on your site if you plan to use one the previous code
Code Snippet to Insert Adsense Ads (#2)
This is a son of the first code, I used AI to make some modifications to it.
This code is gonna place Adsense Ads every three paragraphs.
add_filter('the_content', 'cw_insert_post_ads1');
function cw_insert_post_ads1($content){
if(is_single()){
//ads code
$adsCode = '<div>Insert your ads code here</div>';
$closingP = '</p>';
$contentBlock = explode($closingP, $content);
foreach($contentBlock as $key => $con){
if(trim($con)) {
$contentBlock[$key] .= $closingP;
}
// Insert ads after every third paragraph
if(($key + 1) % 3 == 0){
$contentBlock[$key] .= $adsCode;
}
}
$content = implode('', $contentBlock);
}
return $content;
}
I tested the code using the code snippets plugin and it works well.
Code Snippet to Insert Adsense Ads (#3)
This is another son of the first code, once again, I made modifications to it using an AI tool.
With the help of this code, you can choose where you want to show the ads exactly by specifying the number
add_filter('the_content', 'cw_insert_post_ads1');
function cw_insert_post_ads1($content){
if(is_single()){
//ads code
$adsCode = '<div>Insert your ads code here</div>';
// Paragraph numbers to insert ads after
$insertAfter = array(3, 7, 10, 15);
$closingP = '</p>';
$contentBlock = explode($closingP, $content);
foreach($contentBlock as $key => $con){
if(trim($con)) {
$contentBlock[$key] .= $closingP;
}
// Insert ads after specified paragraph numbers
if(in_array(($key + 1), $insertAfter)){
$contentBlock[$key] .= $adsCode;
}
}
$content = implode('', $contentBlock);
}
return $content;
}
This will add the same ad after every paragraph specified in the code
I tested it and it works as it says it does.
Code Snippet to Insert Adsense Ads (#4)
I found this code in StackOverFlow and it does what you need and you can easily modify it to add more ad units.
I like this one because you can inserter more than one ad code
function prefix_insert_after_paragraph2( $ads, $content ) {
if ( ! is_array( $ads ) ) {
return $content;
}
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
$n = $index + 1;
if ( isset( $ads[ $n ] ) ) {
$paragraphs[$index] .= $ads[ $n ];
}
}
return implode( '', $paragraphs );
}
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
if ( is_single() && ! is_admin() ) {
$content = prefix_insert_after_paragraph2( array(
// The format is: '{PARAGRAPH_NUMBER}' => 'AD_CODE',
'1' => '<div>Ad code after FIRST paragraph goes here</div>',
'2' => '<div>Ad code after SECOND paragraph goes here</div>',
), $content );
}
return $content;
}
You just have to duplicate lines 28 or 29 and change the value.
If you use shortcodes, the code still looks pretty after inserting several ads.
For some reason, this code snippet added an additional ad unit at the end of the post when there were no headings or paragraphs.
Code Snippets to Insert Adsense Ads #5
You are gonna leave money on the table if you have tables, images, and lists and you are not taking them into account.
I modified code #4 using an AI tool so the other HTML tags are also counted.
function prefix_insert_after_paragraph2( $ads, $content ) {
if ( ! is_array( $ads ) ) {
return $content;
}
$tags = 'p|figure|ol|ul'; // The four types of HTML tags to insert ads after
$regex = '/<('.$tags.')([^>]*)>(.*?)<\/\1>/is'; // Regular expression to match the HTML tags
// Get an array of all the matches
preg_match_all( $regex, $content, $matches, PREG_SET_ORDER );
// Loop through the matches
foreach ( $matches as $index => $match ) {
// Get the tag, its attributes, and its contents
$tag = $match[1];
$attributes = $match[2];
$contents = $match[3];
// Build the replacement string
$replacement = '<'.$tag.$attributes.'>'.$contents.'</'.$tag.'>';
// If an ad is specified for the current tag, append it to the replacement string
$n = $index + 1;
if ( isset( $ads[ $n ] ) ) {
$replacement .= $ads[ $n ];
}
// Replace the current tag with the replacement string
$content = str_replace( $match[0], $replacement, $content );
}
return $content;
}
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
if ( is_single() && ! is_admin() ) {
$content = prefix_insert_after_paragraph2( array(
// The format is: '{TAG_NUMBER}' => 'AD_CODE',
'1' => '<div>Ad code after FIRST p, figure, ol, or ul tag goes here</div>',
'2' => '<div>Ad code after SECOND p, figure, ol, or ul tag goes here</div>',
// Add more ads here if needed...
), $content );
}
return $content;
}
I tested the code in a local environment and then in a live site and the code works.
Code Snippet to Insert Adsense Ads (#6)
This code taken from Stack Overflow also did the trick.
As code snippet #4, you can easily modify it to add several ad units
add_filter( 'the_content', 'add_ads_to_content' );
function add_ads_to_content( $content ) {
$ads = array(
2 => 'ad code 1', // paragraph_id => ad_code
4 => 'ad code 2', // paragraph_id => ad_code
6 => 'ad code 3' // paragraph_id => ad_code
);
if ( is_single() && ! is_admin() ) {
foreach ($ads as $paragraph_id => $ad_code) {
$content = prefix_insert_after_paragraph( $ad_code, $paragraph_id, $content );
}
}
return $content;
}
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 );
}
This one didn’t cause any issues when the number of paragraphs or headings isn’t present in the post.
I guess I am gonna stick with this one.
Keep this Mind
Remember not to test these codes on your live sites.
I recommend making a copy of your site and migrating it to a local environment.
Local by Flywheel is the program I use to test code snippets before they are added to the live site.
Keep in mind, that all sites are different and some of these snippets might conflict with plugins or other code snippets on your site.
Also, these are not perfect solutions, they are not meant to work like AdInserter or WPAdvanced ads work.
If you need some level of customization or detail, you will feel less frustrated using a plugin instead of code snippets.