Archived topic
Insert any Code Before H2
5 replies · Started by A. R. Choudhury on November 25, 2021
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)
Modify this condition:
if ( is_single() && ! is_admin() )
Add in_category() for category checking.
https://developer.wordpress.org/reference/functions/in_category/
Add has_tag() for post tag checking.
https://developer.wordpress.org/reference/functions/has_tag/
Example condition: posts with dogs category or cute tag.
if ( ! is_admin() && is_single() || has_tag('cute') || in_category('dogs') )
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.