Guest User

Untitled

a guest
Oct 16th, 2021
129
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. add_filter( 'the_content', 'add_ads_to_content' );
  2.  
  3. function add_ads_to_content( $content ) {
  4.  
  5.     $ads = array(
  6.         2 =>  'ad code 1', // paragraph_id => ad_code
  7.         4 => 'ad code 2', // paragraph_id => ad_code
  8.         6 => 'ad code 3' // paragraph_id => ad_code
  9.     );
  10.  
  11.     if ( is_single() && ! is_admin() ) {
  12.         foreach ($ads as $paragraph_id => $ad_code) {
  13.             $content = prefix_insert_after_paragraph( $ad_code, $paragraph_id, $content );
  14.         }
  15.     }
  16.  
  17.     return $content;
  18. }
  19.  
  20. function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  21.     $closing_p = '</p>';
  22.     $paragraphs = explode( $closing_p, $content );
  23.     foreach ($paragraphs as $index => $paragraph) {
  24.         if ( trim( $paragraph ) ) {
  25.             $paragraphs[$index] .= $closing_p;
  26.         }
  27.         if ( $paragraph_id == $index + 1 ) {
  28.             $paragraphs[$index] .= $insertion;
  29.         }
  30.     }
  31.     return implode( '', $paragraphs );
  32. }
RAW Paste Data