I want to place ads after second paragraph of the posts located under a specific category. For this I am trying to run the following piece of codes but it is not working. Kindly help me out.
//Insert ads after second paragraph of single post content.
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid == 124);
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Insert Ad code here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
}
return $content;
}
// Parent Function that makes the magic happen
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 );
}
CodePudding user response:
you can use this code for it
add_filter('the_content', 'ak_the_content_filter', 10, 1);
function ak_the_content_filter($content)
{
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid != 124) { return $content; }
else{
$parags = explode('</p>', $content);
$parags[1] .= '<br>'.do_shortcode('[SHORTCODE HERE]');// add whatever you want after first paragraph
$content_new = '';
foreach ($parags as $parag) {
$content_new .= $parag;
}
return $content_new;
}
}
}