Replace WordPress’ more tag with advertisement code

Sometime we want to insert Google Adsense or other advertisement code into middle of a post in WordPress. Replacing the <!--more--> code with Google Adsense or other advertisement code is one of the way.

To replace the <!--more--> with advertisement code, we start with defining a pseudo code.

At the single post page (normally single.php), intercept the output of the content.

Find the location and the length of <!--more-->.

Replace <!–more–> with the advertisement code or insert the advertisement code after or before the <!--more--> tag.

Output the modified content.

Let’s assume the single post page of your WordPress theme is single.php. Find the line in single.php where the_content() function is called, replace the line with the following code:

Now we need to define two more functions(replace_more_tag and get_post_middle_ads). You can put the functions either at top of the code in single.php or inside functions.php in your wordpress theme. I would suggestion to put the functions in functions.php for easier maintenance.

When calling the the_content() function, WordPress automatically replace the <!--more--> tag with <p><span id="more-id"></span></p> where the id is the post’s id. So we need to take care of this when writing the replace_more_tag function.

The function finds the <p><span id="more-id"></span></p> in $original and replace it with $replace. If $include_more_tag is true, the <p><span id="more-id"></span></p> will be included. If $include_after is true, it includes the <p><span id="more-id"></span></p> after the $replace else the other way round. Finally the function returns the replaced text.