PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 7, 2022

[FIXED] How to insert ads code before every H2 tags?

 February 07, 2022     php, wordpress     No comments   

Issue

I want to show ads before every h2 tag on my blog. I got an answer here which is only for the first h2 tag. The code is below.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = 'ADS_CODE';

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

    return $content;
}

//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '<h2>';
    $paragraphs = explode( $closing_p, $content );
    if ($paragraphs) {
        $paragraphs[0] = $paragraphs[0].$insertion;
    }    
    return implode( '<h2>', $paragraphs );
}

Solution

With a small change in your code, all headings will be processed

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = 'ADS_CODE';

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

    return $content;
}

//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '<h2>';
    $paragraphs = explode( $closing_p, $content );
    $adv_insert = array_map(fn ($a) => $a . $insertion, $paragraphs);    
    return implode( '<h2>', $adv_insert );
}


Answered By - EM4D
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing