Insert private page content as adverts.
A few years ago a client asked me to inject an advert after the second paragraph of their pages and posts. I found code to insert ads within your post content. It split the content into paragraphs and added the ad content after the second paragraph. I expanded on this code.
The WPBeginner code was quite good but it used hard coded advert content. I created a private page on the client website and pulled in that content as the advert. This allowed the client edit the content easily in a format that they were familiar with.
Last weekend a member of the Genesis WordPress Facebook group asked what Genesis hook to use to automatically add content after 2 paragraphs. I explained that there was no Genesis specific hook and that ‘the_content‘ filter would be needed. I mentioned my code from a few years ago.
Another member replied with code that uses a widget area for the advert content (instead of a page).
I experimented with my modified code and added some functionality to it – it now uses an array of paragraph numbers to add the injected content multiple times.
I also registered a widget area and tried using it for the advert content instead of a page. Each has its merits but the widget area has a small issue that may result in invalid html. The widgets are given a HTML ID so this ID is repeated if the widget area is injected more than once. As IDs must be unique this is invalid markup.
Using a private page (it doesn’t have to be private, this just ensures that it’s not directly accessible by site visitors) allows for the use of a familiar editing interface (and it’s a lot bigger than that used in a Custom HTML widget!).
Here is the result of injecting a page into another page in the Twenty Nineteen theme. It injects the content after the 2nd, 4th, 5th and 8th paragraphs. The content it styled to highlight it (dashed border, smaller font).
It doesn’t work very well on the default Sample Page because it has <blockquote> tags with paragraphs inside them. You can see below that the injected content ends up inside the blockquotes! This is the downside of a simplified injection method, but it’s likely okay most of the time.