Scorpio Liu
Scorpio Liu

Reputation: 11

Insert content after x img tag

My code counts p tags, then insert ads code after x-th p tag. If I want to count img tags, then insert ads code after x-th img tag how should I do it?

add_filter( 'the_content', 'prefix_insert_post_ads2' );

function prefix_insert_post_ads2( $content ) {
    $imgs = preg_match_all("#<img.+>#U", $content, $matches);
    $ad_codea = "ads code"; 
    if ( is_single() && ! is_admin() && $imgs >= 4) {
        return prefix_insert_after_paragraph2( $ad_codea, 3, $content );
    }
    return $content;
}

function prefix_insert_after_paragraph2( $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 );
}

Upvotes: 0

Views: 79

Answers (1)

Scorpio Liu
Scorpio Liu

Reputation: 11

I have solved by myself.

add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
    $imgs = preg_match_all("#<img.+>#U", $content, $matches);
    preg_match_all('/<img[^>]+>/i',$content, $result); 
    $ad_codea = '123';
    if ($imgs < 4 ) {$result[0][1]='';}
    if ( is_single() && ! is_admin()) {
        return str_replace($result[0][1], $result[0][1].$ad_codea, $content);
    }   
}

Upvotes: 1

Related Questions