In this article, we will see how to inject Ads or any piece of HTML code into articles in WordPress.
WordPress is the most popular and powerful CMS (content management system) to date, powering around 25% of the total websites.
It is simple to use and easy to get started with, making it ideal for non-technical people to create a website in no time.
While there are many free and paid plugins available for all types of problems that WordPress owners generally face, using too many of them can drastically affect the performance of your website.
If you are using WordPress for blogging like learnersbucket.com and increasing the reach of your website, you don’t want your users to have a bad experience.
Injecting Ads or pieces of code in between articles in WordPress
You can use this simple code to inject any piece of code, text, or ads, in between your wordpress site.
A WordPress article is composed of Heading tags h1 – h5, paragraphs, spans, images, media, and an unordered and ordered list.
These are the HTML tags that define the content of the articles. Now the injection of code can take before or after any of these tags, mainly paragraphs, as all the text is wrapped under paragraph tags only.
In your theme editor, you can find the themes function.php file. In this file, add the following code.
<?php //Insert ads after the second paragraph of single post content. add_filter( ‘the_content’, ‘prefix_insert_post_ads’ ); function prefix_insert_post_ads( $content ) { $ad_code = ‘<div id=”google-ad-placeholder-192″></div>’; if ( is_single() && ! is_admin() ) { return prefix_insert_after_paragraph( $ad_code, 5, $content ); }return $content; }// Parent Function that makes the magic happen function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { // Change this to H1, H2, or Image to insert after that $closing_p = ‘</p>’; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { // insert after the nth paragraph return implode(”, $paragraphs ); |
Here, we are adding a filter in the single post content. The filter function makes use of the helper function that injects the content after the nth tag.
For example, if you want to inject a piece of code after the 5th paragraph tag.
You can modify this function to inject after any tag or after any count. These ten lines of code are fast, performant, and easy to manage.
You can also stay updated by subscribing to iTechCode.