Random ad code in WordPress post content without plugin

By F.A Mollick

Share on


Well, there are a lots of blogging site owners are earning by putting ad code on their site and most of them using WordPress. Their are lots of plugins available for putting ad code inside your post content. But I want to say you personally that you should always avoid plugins as it can slow down your server. All the ad management plugins has an option panel and to create those options panel the plugin developers use lots of complex PHP codes which can take some more processing time.

But why you need options panel if you can directly write code and it will do the job. In this blog post I am going to show you how to display advertise using advertising code randomly inside the WordPress post content. So lets start-


At first open your theme’s functions.php file with a text editor.

Than put the below code at the end of your functions.php file:

//Insert ads between first and fourth paragraph of single post content to show it randomly between first and second paragraph.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
 // Add code for mobile
 $ad_code_mobile = 'AD CODE FOR MOBILE';
 // Add code for PC
 if ( is_single() && ! is_admin() ) {
 if (!wp_is_mobile()) {
 $randnumpc = mt_rand(1,4);
 return prefix_insert_after_paragraph( $ad_code_pc, $randnumpc, $content );
 else {
 $randnummobi = mt_rand(1,4);
 return prefix_insert_after_paragraph( $ad_code_mobile, $randnummobi, $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 );

After adding the PHP code inside the functions.php file just add your ad code where you can see red code. You can notice that there are two line of codes. First one will be visible on mobile , and the second one is for desktop or laptop. The below line of code you can see inside the above code indicate that the ad code will be shown anywhere between first paragraph to fourth paragraph.

 $randnummobi = mt_rand(1,4);

That is all you need. Now try it.

Comments are closed.