How to insert ads right after X paragraph in wordpress

I’m using a code on my wordpress site that shows an ads right after 8th paragraph.
How can i make it something like. uhmm. “do NOT show the ads if content have less than 8 paragraphs”

Thanks in advance.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '<div>ads code</div>';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 8, $content );
    }

    return $content;
}

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 );
}

Related posts

1 comment

  1. If all you want to do is make sure that no ad is shown if the content is shorter than what your function allows, simply wrap the foreach block inside a small check:

    function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        if (count($paragraphs) >= $insertion) {
            foreach ($paragraphs as $index => $paragraph) {
    
                if ( trim( $paragraph ) ) {
                    $paragraphs[$index] .= $closing_p;
                }
    
                if ( $paragraph_id == $index + 1 ) {
                    $paragraphs[$index] .= $insertion;
                }
            }
    
            return implode( '', $paragraphs );
        }
    
        return $content;
    }
    

    I’m not sure if this was what you were planning to do, but at least that’s what I interpreted 🙂

    What this does is basically check if you have more paragraphs than are needed for the ad to show, and then runs the loop. Otherwise, it will just return the content. The reason for it returning the content is so that prefix_insert_post_ads has consistent behaviour.

Comments are closed.