Insert Ads in WordPress Content Without a Plugin
By modifying your theme's functions.php file, you can insert ad code (e.g., after the second paragraph) directly into your post content without installing a plugin. This method offers greater flexibility and control over the code.
Implementation Steps
Add the following code to the end of your active theme's functions.php file:
// Insert ad after the second paragraph in single posts
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'Place your ad code here (e.g., Google AdSense)';
if ( is_single() && ! is_admin() ) {
// Change the number 2 to target a different paragraph
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Core function: Insert content after a specific paragraph
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_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 );
}
Code Explanation & Customization
- Ad Code: Replace the
<div>Place your ad code here...</div>placeholder with your own ad HTML or JavaScript. - Ad Position: The ad appears after the second paragraph by default. To change this, modify the second argument (
2) in the call toprefix_insert_after_paragraphinside theprefix_insert_post_adsfunction (e.g., use3for after the third paragraph). - Scope: The
is_single()condition ensures the ad only appears on single post pages in the front end, not in the admin area.
Alternative: Using a Plugin
If you prefer not to edit code, you can use a dedicated plugin like Insert Post Ads. Plugins provide a graphical interface for managing multiple ad placements and insertion rules more conveniently.
Important: Always back up your theme files before making changes. If you use a child theme, add the code to the child theme's
functions.phpto prevent your modifications from being overwritten during theme updates.