Site logo

Archived topic

Insert any Code Before H2

5 replies · Started by A. R. Choudhury on November 25, 2021

Viewing posts 1–6 of 6

Hello,

I want to add my AdSense code or any of my custom image ad before every H2 tag in every post (excluding all pages and specific post categories and tags).

But there is no hook.

Is it possible through custom code?

I have tried every ad manager plugin. But no plugin can add ad code to every H2 tag in every post. Please help.

My website: https://www.nutritioncrown.com/

Hi there,

You can try something like this:

add_filter( 'the_content', 'insert_element', 20 );
function insert_element( $content ) {
    global $post;
    $inserted_element = 'your ads here';
    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_h2( $inserted_element, 1, $content );
    }
    return $content;
}
function prefix_insert_after_h2( $insertion, $h2_id, $content ) {
  $closing_h2 = '</h2>';
  $h2s = explode( $closing_h2, $content );
  foreach ($h2s as $index => $h2) {
    if ( trim( $h2 ) ) {
     $h2s[$index] .= $closing_h2.$insertion;
    }
  }
  return implode( '', $h2s );
}

Replace the line your ads here with whatever element you want to add in. :)

Thanks, Elvin. But how can I exclude page, specific category or tags? (Sorry, I'm not a coder)

And for page exclusion?

You'll have to modify the code and add an exclusion condition.

Example:

add_filter( 'the_content', 'insert_element', 20 );
function insert_element( $content ) {
    global $post;
    $exclusion = array(123,456,789);
    $inserted_element = 'your ads here';
    if ( is_single() && ! is_admin() ) {
        if(in_array( $post->ID, $exclusion )){
            return;
        }
        else {
            return prefix_insert_after_h2( $inserted_element, 1, $content );
        }
    }
    return $content;
}
function prefix_insert_after_h2( $insertion, $h2_id, $content ) {
  $closing_h2 = '</h2>';
  $h2s = explode( $closing_h2, $content );
  foreach ($h2s as $index => $h2) {
    if ( trim( $h2 ) ) {
     $h2s[$index] .= $closing_h2.$insertion;
    }
  }
  return implode( '', $h2s );
}

You then modify the array values in $exclusion = array(123,456,789); to the page ids to be excluded.

This archived topic is closed to new replies.