How do I show google ads between post content?

I want to show ads by Google between text content, like show 3 ads one after 1st para second after 3rd para and one at end of last para.

I know i have to modify in single.php but being novice in php I am unable to do this.

Would be real helpful if someone could help me do this. Thanks.

Topic single ads adsense Wordpress

Category Web


You can use a shortcode or the_content filter. I think the_content filter is better because your don't introduce any string in your post, so the content can be exported and used in another platforms if needed. For emxample, for show a block of adsense after the first parragraph:

 add_filter( 'the_content', 'tbn_ads_inside_content' );
 function tbn_ads_inside_content( $content ) {
     
      $output = $content;
      //We don't want to modify the_content in de admin area
      if( !is_admin() ) {
          $ads = "<p>your_ads_code</p>";
          $p_array = explode('</p>', $content );
          $p_count = 1;

          if( !empty( $p_array ) ){

              array_splice( $p_array, $p_count, 0, $ads );
              $output = '';

              foreach( $p_array as $key=>$value ){

                  $output .= $value;

               }
          }

      }

      return $output;

 }

Here is the function I use to add a widget after the second paragraph in a post. This is only for the first post and single posts, so you will need to tweak it a bit if you need to show this in all posts. You should be able to modify this to suit your needs. Hope this helps

// Add advertising widget within the firts post and single posts
function pietergoosen_insert_content_after_second_paragraph_filter( $content ) {
    static $first;
    $first = (!isset($first)) ? true : false;
    if (true == $first) {
      ob_start();
      echo '<div class="widget-box">';
         dynamic_sidebar( 'sidebar-19' );
         echo '</div><!-- end .widget-box -->';

      $new_content = ob_get_clean();
      if ( ! is_admin() ) {
          return pietergoosen_insert_content_after_second_paragraph( $new_content, 2, $content );
      }
    }
    return $content;
}
add_filter('the_content','pietergoosen_insert_content_after_second_paragraph_filter');

// Paragraph explode and insert
function pietergoosen_insert_content_after_second_paragraph( $new_content, $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] .= $new_content;
        }
    }
    return implode( '', $paragraphs );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.