Custom AdSense code in functions.php is breaking my site

I have been using Schema theme in one of my sites. I have been using a child theme and in functions.php I have inserted a custom code to display Google AdSense code after 4th paragraph.


It is breaking my site.

// Middle of the content ads
add_filter('the_content', 'wpse_ad_content');

function wpse_ad_content($content)
{
    if (!is_single()) return $content;
    $paragraphAfter = 4;
    $content = explode("</p>", $content);
    $new_content = '';
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $paragraphAfter) {
            $new_content.= 'AdSense Code';
            $new_content.= '</div>';
        }

        $new_content.= $content[$i] . "</p>";
    }

    return $new_content;
}

Here is the code I have used. Found it on Stackoverflow.

Try this way

<?php
  
//Insert ads after fourth paragraph of single post content.
 
add_filter( 'the_content', 'prefix_insert_post_ads' );
 
function prefix_insert_post_ads( $content ) {
     
    $ad_code = '<div>Ads code goes here</div>';
 
    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 4, $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 );
}
// Source: http://wpbeg.in/9obQwn
1 Like

Thank You @GulshanKumar Bro :wink:

You’re welcome!

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.