• I want to show adsense ads below the 4th and 20th paragraph of every blog post, ONLY if there is a 20th paragraph.

    I managed to place the adsense below the 4th ad by placing the following code in my functions.php file, however I don’t know how to add an additional ad after the 20th.

    //Insert ads after second paragraph of single post content.
    
    add_filter( 'the_content', 'prefix_insert_post_ads' );
    
    function prefix_insert_post_ads( $content ) {
    
    $ad_code = '<div style="float:left;padding: 15px;"><script type="text/javascript">
        google_ad_client = "ca-pub-xxxxxxxxxxxx";
        google_ad_slot = "xxxxxxxxxx";
        google_ad_width = 300;
        google_ad_height = 250;
    </script>
    <!-- Malben -->
    <script type="text/javascript"
    src="//pagead2.googlesyndication.com/pagead/show_ads.js">
    </script></div>';
    
    if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $ad_code, 3, $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 );
    }

    Please assist, thank you 🙂

Viewing 1 replies (of 1 total)
  • Here is a similar example. I was using twentysixteen as my main theme and needed something like that. You might want to change some stuff because you don’t mention your own theme.

    Assuming that each paragraph is cut via a
    then the code would be like that:

    function adify_paragraphs($content) {
    	$tmp = $content;
    	$tmp = explode('<br />',$content);
    	$adcode = "<span style='color:red;'>hahaw</span>"; //replace with ad code here.
    	if (count($tmp)>4):
    			array_splice($tmp,4,0,$adcode);
    	endif;
    	if (count($tmp)>20):
    			array_splice($tmp,20,0,$adcode);
    	endif;
    	$cc = implode("<br/>",$tmp);
    	return $cc;
    }
    add_filter( 'the_content', 'adify_paragraphs');

    If indeed you have paragraphs (<p>..</p>) then the starting code should be changed like this:

    function adify_paragraphs($content) {
    	$tmp = $content;
    	$tmp = explode('</p>',$content);
    	$adcode = "<p><span style='color:red;'>hahaw</span>";
    	if (count($tmp)>4):
    			array_splice($tmp,4,0,$adcode);
    	endif;
    	if (count($tmp)>20):
    			array_splice($tmp,20,0,$adcode);
    	endif;
    	$cc = implode("<p/>",$tmp);
    	return $cc;
    }
    add_filter( 'the_content', 'adify_paragraphs');
Viewing 1 replies (of 1 total)
  • The topic ‘Adding ad code below X paragraphs?’ is closed to new replies.