How To Insert Ads After The First Paragraph Of Your Post

Sometimes you might need to insert your Ads (e.g. Google Adsense) after the first paragraph of your post.

This PHP snippet automatically inserts your Ads after the first paragraph found in your post content.

Without any plugin. All you need to do is to copy and paste the snippets into your WordPress file.

How to use it:

1. Login to your WordPress admin panel.

2. Click the Editor link under the Appearance section of the dashboard.

Edit WordPress Template

3. Click the Theme Functions link on the right hand side of the Edit Themes page.

Edit Theme Functions

4. Copy and add the following PHP snippets to the end of the functions.php.

// Insert ads after first paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
  $ad_code = 'Your Ads Code Here';
  if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $ad_code, 1, $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 );
}

5. Click the Update File button and done.
Update Theme File
Last Thoughts:

If you’re not certain how to insert the PHP snippets into your PHP file. Here is a list of 7 best WordPress Ads Management plugins that help you quickly place your ads into anywhere on your WordPress website without any PHP skill. Have fun.

Rate This Article
Sending
User Review
2.75 (8 votes)