Throughout my website career, I’ve found google adsense to be a very effective method to earn income. Even though it may not be the best for every site, it certainly has an ingenious method of displaying ads.
Unfortunately, WordPress users may have a tough time implementing google adsense without a plugin. For those of you who love to do it yourself, here is a simple way to place adsense on your own WordPress blog.
To accomplish this task easily, we will use PHP Simple HTML DOM Parser. This PHP script enables an easy way of accessing HTML tags and modifying them.
I suggest placing the code created in this tutorial inside the functions.php
file of your WordPress theme. It will then be available for use in all of your other WordPress documents.
First, include the parser:
include_once("simple_html_dom.php");
Now we can move on to creating the function add_ga( $content )
which will add Google Adsense code to the given $content
variable and return the new string.
The parser requires HTML to work with. Thus, it is necessary to obtain this from the given string:
$content = str_get_html( $content );
Next, let’s find all the paragraph elements inside the given content:
$p = $content->find('p');
For every fifth element, we can append Google Adsense code. Feel free to customize this number, as it all depends on the average length of your paragraphs!
$paragraph_offset = 5; # Customize this for your own needs!
for( $i = 1; $i < = $paragraph_offset * 2 + 1; $i += $paragraph_offset ) {
if ( isset( $p[$i] ) ) {
$p[$i]->outertext = $p[$i]->outertext."<div class="adsense">Your Google Adsense Code</div>";
}
}
Remember to replace Your Google Adsense Code
with the code you generate from your own profile. You may style the position of the ads (floated left, right, or center) using the surrounding div
element. Furthermore, please take note on how this only displays a max of three ad units, as stated by the Google Adsense Program Policies.
To wrap it all up, don’t forget to return the new content:
return $content;
And that’s it! Here is the final code:
include_once("simple_html_dom.php");
function add_ga( $content ) {
$content = str_get_html( $content );
$p = $content->find('p');
$paragraph_offset = 5; # Customize this for your own needs!
for( $i = 1; $i < = $paragraph_offset * 2 + 1; $i += $paragraph_offset ) {
if ( isset( $p[$i] ) ) {
$p[$i]->outertext = $p[$i]->outertext."<div class="adsense">Your Google Adsense Code</div>";
}
}
return $content;
}
Place the following code in your single.php
to use this function:
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo add_ga( $content );
Thank you for reading!